forked from juj/MathGeoLib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPolyhedron.cpp
3290 lines (2928 loc) · 93.7 KB
/
Polyhedron.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 Jukka Jylänki
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */
/** @file Polyhedron.cpp
@author Jukka Jylänki
@brief Implementation for the Polyhedron geometry object. */
#include "Polyhedron.h"
#include <set>
#include <map>
#include <utility>
#include <list>
#include <sstream>
#include <stdlib.h>
#include "../Math/assume.h"
#include "../Math/MathFunc.h"
#include "../Math/float3x3.h"
#include "../Math/float3x4.h"
#include "../Math/float4x4.h"
#include "../Math/Quat.h"
#include "AABB.h"
#include "OBB.h"
#include "Frustum.h"
#include "Plane.h"
#include "Polygon.h"
#include "Line.h"
#include "Ray.h"
#include "LineSegment.h"
#include "Triangle.h"
#include "Sphere.h"
#include "Capsule.h"
#include "../Algorithm/Random/LCG.h"
#include "../Time/Clock.h"
#if __cplusplus > 199711L // Is C++11 or newer?
#define HAS_UNORDERED_MAP
#endif
#ifdef HAS_UNORDERED_MAP
#include <unordered_map>
#else
#include <map>
#endif
#ifdef MATH_GRAPHICSENGINE_INTEROP
#include "VertexBuffer.h"
#endif
#define MATH_CONVEXHULL_DOUBLE_PRECISION
#ifdef MATH_CONVEXHULL_DOUBLE_PRECISION
#include "../Math/float4d.h"
#endif
MATH_BEGIN_NAMESPACE
#ifdef MATH_CONVEXHULL_DOUBLE_PRECISION
typedef float4d cv;
typedef double cs;
#if defined(_MSC_VER) && defined(MATH_AUTOMATIC_SSE) && defined(MATH_SSE2)
typedef std::vector<double4_storage, AlignedAllocator<double4_storage, 16> > VecdArray;
#else
typedef std::vector<float4d> VecdArray;
#endif
#else
typedef vec cv;
typedef float cs;
typedef VecArray VecdArray;
#endif
void Polyhedron::Face::FlipWindingOrder()
{
for(size_t i = 0; i < v.size()/2; ++i)
Swap(v[i], v[v.size()-1-i]);
}
std::string Polyhedron::Face::ToString() const
{
std::stringstream ss;
for(size_t i = 0; i < v.size(); ++i)
ss << v[i] << ((i!=v.size()-1) ? ", " : "");
return ss.str();
}
Polyhedron::Face Polyhedron::Face::FromString(const char *str)
{
Face f;
if (!str)
return f;
while(*str)
{
char *endptr = 0;
int idx = (int)strtol(str, &endptr, 10);
str = endptr;
while(*str == ',' || *str == ' ')
++str;
f.v.push_back(idx);
}
return f;
}
int Polyhedron::NumEdges() const
{
int numEdges = 0;
for(size_t i = 0; i < f.size(); ++i)
numEdges += (int)f[i].v.size();
return numEdges / 2;
}
vec Polyhedron::Vertex(int vertexIndex) const
{
assume(vertexIndex >= 0);
assume(vertexIndex < (int)v.size());
#ifndef MATH_ENABLE_INSECURE_OPTIMIZATIONS
if (vertexIndex < 0 || vertexIndex >= (int)v.size())
return vec::nan;
#endif
return v[vertexIndex];
}
LineSegment Polyhedron::Edge(int edgeIndex) const
{
assume(edgeIndex >= 0);
LineSegmentArray edges = Edges();
assume(edgeIndex < (int)edges.size());
#ifndef MATH_ENABLE_INSECURE_OPTIMIZATIONS
if (edgeIndex < 0 || edgeIndex >= (int)edges.size())
return LineSegment(vec::nan, vec::nan);
#endif
return edges[edgeIndex];
}
LineSegmentArray Polyhedron::Edges() const
{
std::vector<std::pair<int, int> > edges = EdgeIndices();
LineSegmentArray edgeLines;
edgeLines.reserve(edges.size());
for(size_t i = 0; i < edges.size(); ++i)
edgeLines.push_back(LineSegment(Vertex(edges[i].first), Vertex(edges[i].second)));
return edgeLines;
}
std::vector<std::pair<int, int> > Polyhedron::EdgeIndices() const
{
std::set<std::pair<int, int> > uniqueEdges;
for(int i = 0; i < NumFaces(); ++i)
{
assume(f[i].v.size() >= 3);
if (f[i].v.size() < 3)
continue; // Degenerate face with less than three vertices, skip!
int x = f[i].v.back();
for(size_t j = 0; j < f[i].v.size(); ++j)
{
int y = f[i].v[j];
uniqueEdges.insert(std::make_pair(Min(x, y), Max(x, y)));
x = y;
}
}
std::vector<std::pair<int, int> >edges;
edges.insert(edges.end(), uniqueEdges.begin(), uniqueEdges.end());
return edges;
}
std::vector<Polygon> Polyhedron::Faces() const
{
std::vector<Polygon> faces;
faces.reserve(NumFaces());
for(int i = 0; i < NumFaces(); ++i)
faces.push_back(FacePolygon(i));
return faces;
}
Polygon Polyhedron::FacePolygon(int faceIndex) const
{
Polygon p;
assume(faceIndex >= 0);
assume(faceIndex < (int)f.size());
#ifndef MATH_ENABLE_INSECURE_OPTIMIZATIONS
if (faceIndex < 0 || faceIndex >= (int)f.size())
return Polygon();
#endif
p.p.reserve(f[faceIndex].v.size());
for(size_t i = 0; i < f[faceIndex].v.size(); ++i)
p.p.push_back(Vertex(f[faceIndex].v[i]));
return p;
}
Plane Polyhedron::FacePlane(int faceIndex) const
{
const Face &face = f[faceIndex];
if (face.v.size() >= 3)
return Plane(v[face.v[0]], v[face.v[1]], v[face.v[2]]);
else if (face.v.size() == 2)
return Plane(Line(v[face.v[0]], v[face.v[1]]), ((vec)v[face.v[0]]-(vec)v[face.v[1]]).Perpendicular());
else if (face.v.size() == 1)
return Plane(v[face.v[0]], DIR_VEC(0,1,0));
else
return Plane();
}
cv PolyFaceNormal(const Polyhedron &poly, int faceIndex)
{
const Polyhedron::Face &face = poly.f[faceIndex];
if (face.v.size() == 3)
{
cv a = DIR_TO_FLOAT4(poly.v[face.v[0]]);
cv b = DIR_TO_FLOAT4(poly.v[face.v[1]]);
cv c = DIR_TO_FLOAT4(poly.v[face.v[2]]);
cv normal = (b-a).Cross(c-a);
normal.Normalize();
return normal;
// return ((vec)v[face.v[1]]-(vec)v[face.v[0]]).Cross((vec)v[face.v[2]]-(vec)v[face.v[0]]).Normalized();
}
else if (face.v.size() > 3)
{
// Use Newell's method of computing the face normal for best stability.
// See Christer Ericson, Real-Time Collision Detection, pp. 491-495.
cv normal(0, 0, 0, 0);
int v0 = face.v.back();
for(size_t i = 0; i < face.v.size(); ++i)
{
int v1 = face.v[i];
normal.x += (cs(poly.v[v0].y) - poly.v[v1].y) * (cs(poly.v[v0].z) + poly.v[v1].z); // Project on yz
normal.y += (cs(poly.v[v0].z) - poly.v[v1].z) * (cs(poly.v[v0].x) + poly.v[v1].x); // Project on xz
normal.z += (cs(poly.v[v0].x) - poly.v[v1].x) * (cs(poly.v[v0].y) + poly.v[v1].y); // Project on xy
v0 = v1;
}
normal.Normalize();
return normal;
#if 0
cv bestNormal;
cs bestLen = -FLOAT_INF;
cv a = poly.v[face.v[face.v.size()-2]];
cv b = poly.v[face.v.back()];
for(size_t i = 0; i < face.v.size()-2; ++i)
{
cv c = poly.v[face.v[i]];
cv normal = (c-b).Cross(a-b);
float len = normal.Normalize();
if (len > bestLen)
{
bestLen = len;
bestNormal = normal;
}
a = b;
b = c;
}
assert(bestLen != -FLOAT_INF);
return DIR_VEC((float)bestNormal.x, (float)bestNormal.y, (float)bestNormal.z);
#endif
#if 0
// Find the longest edge.
cs bestLenSq = -FLOAT_INF;
cv bestEdge;
int v0 = face.v.back();
int bestV0 = 0;
int bestV1 = 0;
for(size_t i = 0; i < face.v.size(); ++i)
{
int v1 = face.v[i];
cv edge = cv(poly.v[v1]) - cv(poly.v[v0]);
cs lenSq = edge.Normalize();
if (lenSq > bestLenSq)
{
bestLenSq = lenSq;
bestEdge = edge;
bestV0 = v0;
bestV1 = v1;
}
v0 = v1;
}
cv bestNormal;
cs bestLen = -FLOAT_INF;
for(size_t i = 0; i < face.v.size(); ++i)
{
if (face.v[i] == bestV0 || face.v[i] == bestV1)
continue;
cv edge = cv(poly.v[i]) - cv(poly.v[bestV0]);
edge.Normalize();
cv normal = bestEdge.Cross(edge);
cs len = normal.Normalize();
if (len > bestLen)
{
bestLen = len;
bestNormal = normal;
}
}
assert(bestLen != -FLOAT_INF);
return DIR_VEC((float)bestNormal.x, (float)bestNormal.y, (float)bestNormal.z);
#endif
}
else if (face.v.size() == 2)
return DIR_TO_FLOAT4(((vec)poly.v[face.v[1]]-(vec)poly.v[face.v[0]]).Cross(((vec)poly.v[face.v[0]]-(vec)poly.v[face.v[1]]).Perpendicular()-poly.v[face.v[0]]).Normalized());
else if (face.v.size() == 1)
return cv(0, 1, 0, 0);
else
return float4::nan;
}
vec Polyhedron::FaceNormal(int faceIndex) const
{
cv normal = PolyFaceNormal(*this, faceIndex);
return DIR_VEC((float)normal.x, (float)normal.y, (float)normal.z);
}
int Polyhedron::ExtremeVertex(const vec &direction) const
{
int mostExtreme = -1;
float mostExtremeDist = -FLT_MAX;
for(int i = 0; i < NumVertices(); ++i)
{
float d = Dot(direction, Vertex(i));
if (d > mostExtremeDist)
{
mostExtremeDist = d;
mostExtreme = i;
}
}
return mostExtreme;
}
vec Polyhedron::ExtremePoint(const vec &direction) const
{
return Vertex(ExtremeVertex(direction));
}
vec Polyhedron::ExtremePoint(const vec &direction, float &projectionDistance) const
{
vec extremePoint = ExtremePoint(direction);
projectionDistance = extremePoint.Dot(direction);
return extremePoint;
}
int Polyhedron::ExtremeVertexConvex(const std::vector<std::vector<int> > &adjacencyData, const vec &direction,
std::vector<unsigned int> &floodFillVisited, unsigned int floodFillVisitColor,
float &mostExtremeDistance, int startingVertex) const
{
#ifdef MATH_NUMSTEPS_STATS
numSearchStepsDone = 0;
numImprovementsMade = 0;
#endif
float curD = direction.Dot(this->v[startingVertex]);
const int *neighbors = &adjacencyData[startingVertex][0];
const int *neighborsEnd = neighbors + adjacencyData[startingVertex].size();
floodFillVisited[startingVertex] = floodFillVisitColor;
int secondBest = -1;
float secondBestD = curD - 1e-3f;
while(neighbors != neighborsEnd)
{
#ifdef MATH_NUMSTEPS_STATS
++numSearchStepsDone;
#endif
int n = *neighbors++;
if (floodFillVisited[n] != floodFillVisitColor)
{
float d = direction.Dot(this->v[n]);
if (d > curD)
{
#ifdef MATH_NUMSTEPS_STATS
++numImprovementsMade;
#endif
startingVertex = n;
curD = d;
floodFillVisited[startingVertex] = floodFillVisitColor;
neighbors = &adjacencyData[startingVertex][0];
neighborsEnd = neighbors + adjacencyData[startingVertex].size();
secondBest = -1;
secondBestD = curD - 1e-3f;
}
else if (d > secondBestD)
{
secondBest = n;
secondBestD = d;
}
}
}
if (secondBest != -1 && floodFillVisited[secondBest] != floodFillVisitColor)
{
float secondMostExtreme = -FLOAT_INF;
#ifdef MATH_NUMSTEPS_STATS
int numSearchStepsDoneParent = numSearchStepsDone;
int numImprovementsMadeParent = numImprovementsMade;
#endif
int secondTry = ExtremeVertexConvex(adjacencyData, direction, floodFillVisited, floodFillVisitColor, secondMostExtreme, secondBest);
#ifdef MATH_NUMSTEPS_STATS
numSearchStepsDone += numSearchStepsDoneParent;
numImprovementsMade += numImprovementsMadeParent;
#endif
if (secondMostExtreme > curD)
{
mostExtremeDistance = secondMostExtreme;
return secondTry;
}
}
mostExtremeDistance = curD;
return startingVertex;
#if 0
float curD = direction.Dot(this->v[startingVertex]);
for(;;)
{
const std::vector<int> &neighbors = adjacencyData[startingVertex];
float bestD = curD - 1e-3f;
int bestNeighbor = -1;
floodFillVisited[startingVertex] = floodFillVisitColor;
for(size_t i = 0; i < neighbors.size(); ++i)
{
float d = direction.Dot(this->v[neighbors[i]]);
if (d > curD + 1e-3f)
{
startingVertex = bestNeighbor;
curD = d;
break;
}
if (d > bestD)
{
bestD = d;
bestNeighbor = neighbors[i];
}
}
if (bestNeighbor == -1 || floodFillVisited[bestNeighbor] == floodFillVisitColor)
{
mostExtremeDistance = curD;
return startingVertex;
}
else
{
startingVertex = bestNeighbor;
curD = bestD;
}
}
#endif
#if 0
mostExtremeDistance = Dot(direction, Vertex(startingVertex));
int prevVertex;
do
{
prevVertex = startingVertex;
const std::vector<int> &neighbors = adjacencyData[startingVertex];
for(size_t i = 0; i < neighbors.size(); ++i)
{
int v = neighbors[i];
if (floodFillVisited[v] == floodFillVisitColor)
continue;
floodFillVisited[v] = floodFillVisitColor;
float d = direction.Dot(this->v[v]);
if (d > mostExtremeDistance)
{
mostExtremeDistance = d;
startingVertex = v;
break;
}
if (d > mostExtremeDistance - 1e-3f)
{
float subSearchMostExtreme;
int ev = ExtremeVertexConvex(adjacencyData, direction, floodFillVisited, floodFillVisitColor, subSearchMostExtreme, v);
if (subSearchMostExtreme > mostExtremeDistance)
{
mostExtremeDistance = subSearchMostExtreme;
startingVertex = ev;
break;
}
}
}
} while(prevVertex != startingVertex);
return startingVertex;
#endif
}
void Polyhedron::ProjectToAxis(const vec &direction, float &outMin, float &outMax) const
{
///\todo Optimize!
vec minPt = ExtremePoint(-direction);
vec maxPt = ExtremePoint(direction);
outMin = Dot(minPt, direction);
outMax = Dot(maxPt, direction);
}
vec Polyhedron::ApproximateConvexCentroid() const
{
// Since this shape is convex, the averaged position of all vertices is inside this polyhedron.
vec arbitraryCenterVertex = vec::zero;
for(int i = 0; i < NumVertices(); ++i)
arbitraryCenterVertex += Vertex(i);
return arbitraryCenterVertex / (float)NumVertices();
}
vec Polyhedron::ConvexCentroid() const
{
if (v.size() <= 3)
{
if (v.size() == 3)
return (vec(v[0]) + vec(v[1]) + vec(v[2])) / 3.f;
else if (v.size() == 2)
return (vec(v[0]) + vec(v[1])) / 2.f;
else if (v.size() == 1)
return vec(v[0]);
else
return vec::nan;
}
// Since this shape is convex, the averaged position of all vertices is inside this polyhedron.
vec arbitraryCenterVertex = ApproximateConvexCentroid();
vec centroid = vec::zero;
float totalVolume = 0.f;
// Decompose the polyhedron to tetrahedrons and compute the mass of center of each, and the total
// mass of center of the polyhedron will be the weighted average of the tetrahedrons' mass of centers.
for(size_t i = 0; i < f.size(); ++i)
{
const Face &fa = f[i];
if (fa.v.size() < 3)
continue;
for(int j = 0; j < (int)fa.v.size()-2; ++j)
{
vec a = Vertex(fa.v[j]);
vec b = Vertex(fa.v[j+1]);
vec c = Vertex(fa.v[j+2]);
vec center = (a + b + c + arbitraryCenterVertex) * 0.25f;
float volume = Abs((a - arbitraryCenterVertex).Dot((b - arbitraryCenterVertex).Cross(c - arbitraryCenterVertex))); // This is actually volume*6, but can ignore the scale.
totalVolume += volume;
centroid += volume * center;
}
}
return centroid / totalVolume;
}
float Polyhedron::SurfaceArea() const
{
float area = 0.f;
for(int i = 0; i < NumFaces(); ++i)
{
if (f[i].v.size() < 3)
continue; // Silently ignore degenerate faces.
area += FacePolygon(i).Area(); ///@todo Optimize temporary copies.
}
return area;
}
/** The implementation of this function is based on Graphics Gems 2, p. 170: "IV.1. Area of Planar Polygons and Volume of Polyhedra." */
float Polyhedron::Volume() const
{
float volume = 0.f;
for(int i = 0; i < NumFaces(); ++i)
{
if (f[i].v.size() < 3)
continue; // Silently ignore degenerate faces.
Polygon face = FacePolygon(i); ///@todo Optimize temporary copies.
volume += face.Vertex(0).Dot(face.NormalCCW()) * face.Area();
}
return Abs(volume) / 3.f;
}
AABB Polyhedron::MinimalEnclosingAABB() const
{
AABB aabb;
aabb.SetNegativeInfinity();
for(int i = 0; i < NumVertices(); ++i)
aabb.Enclose(Vertex(i));
return aabb;
}
#ifdef MATH_CONTAINERLIB_SUPPORT
OBB Polyhedron::MinimalEnclosingOBB() const
{
return OBB::OptimalEnclosingOBB((vec*)&v[0], (int)v.size());
}
#endif
bool Polyhedron::FaceIndicesValid() const
{
// Test condition 1: Face indices in proper range.
for(int i = 0; i < NumFaces(); ++i)
for(int j = 0; j < (int)f[i].v.size(); ++j)
if (f[i].v[j] < 0 || f[i].v[j] >= (int)v.size())
return false;
// Test condition 2: Each face has at least three vertices.
for(int i = 0; i < NumFaces(); ++i)
if (f[i].v.size() < 3)
return false;
// Test condition 3: Each face may refer to a vertex at most once. (Complexity O(n^2)).
for(int i = 0; i < NumFaces(); ++i)
for(int j = 0; j < (int)f[i].v.size(); ++j)
for(size_t k = j+1; k < f[i].v.size(); ++k)
if (f[i].v[j] == f[i].v[k])
return false;
return true;
}
void Polyhedron::FlipWindingOrder()
{
for(size_t i = 0; i < f.size(); ++i)
f[i].FlipWindingOrder();
}
bool Polyhedron::IsClosed() const
{
std::set<std::pair<int, int> > uniqueEdges;
for(int i = 0; i < NumFaces(); ++i) // O(F)
{
if (f[i].v.empty())
continue;
assume1(FacePolygon(i).IsPlanar(), FacePolygon(i).SerializeToString());
assume(FacePolygon(i).IsSimple());
int x = f[i].v.back();
for(size_t j = 0; j < f[i].v.size(); ++j) // O(1)
{
int y = f[i].v[j];
if (uniqueEdges.find(std::make_pair(x, y)) != uniqueEdges.end()) // O(logE)
{
LOGW("The edge (%d,%d) is used twice. Polyhedron is not simple and closed!", x, y);
return false; // This edge is being used twice! Cannot be simple and closed.
}
uniqueEdges.insert(std::make_pair(x, y)); // O(logE)
x = y;
}
}
for(std::set<std::pair<int, int> >::iterator iter = uniqueEdges.begin();
iter != uniqueEdges.end(); ++iter)
{
std::pair<int, int> reverse = std::make_pair(iter->second, iter->first);
if (uniqueEdges.find(reverse) == uniqueEdges.end())
{
LOGW("The edge (%d,%d) does not exist. Polyhedron is not closed!", iter->second, iter->first);
return false;
}
}
return true;
}
bool Polyhedron::IsConvex() const
{
// This function is O(n^2).
/** @todo Real-Time Collision Detection, p. 64:
A faster O(n) approach is to compute for each face F of P the centroid C of F,
and for all neighboring faces G of F test if C lies behind the supporting plane of
G. If some C fails to lie behind the supporting plane of one or more neighboring
faces, P is concave, and is otherwise assumed convex. However, note that just as the
corresponding polygonal convexity test may fail for a pentagram this test may fail for,
for example, a pentagram extruded out of its plane and capped at the ends. */
float farthestD = -FLOAT_INF;
int numPointsOutside = 0;
for(size_t i = 0; i < f.size(); ++i)
{
if (f[i].v.empty())
continue;
vec pointOnFace = v[f[i].v[0]];
vec faceNormal = FaceNormal((int)i);
for(size_t j = 0; j < v.size(); ++j)
{
float d = faceNormal.Dot(vec(v[j]) - pointOnFace);
if (d > 1e-2f)
{
if (d > farthestD)
farthestD = d;
++numPointsOutside;
// LOGW("Distance of vertex %s/%d from face %s/%d: %f",
// Vertex(j).ToString().c_str(), (int)j, FacePlane(i).ToString().c_str(), (int)i, d);
// return false;
}
}
}
if (numPointsOutside > 0)
{
LOGW("%d point-planes are outside the face planes. Farthest is at distance %f!", numPointsOutside, farthestD);
return false;
}
return true;
}
bool Polyhedron::EulerFormulaHolds() const
{
return NumVertices() + NumFaces() - NumEdges() == 2;
}
bool Polyhedron::FacesAreNondegeneratePlanar(float epsilon) const
{
for(int i = 0; i < (int)f.size(); ++i) // O(F)
{
const Face &face = f[i];
if (face.v.size() < 3)
return false;
float area = FacePolygon(i).Area(); // O(1)
if (!(area > 0.f)) // Test with negation for NaNs.
return false;
if (face.v.size() >= 4)
{
Plane facePlane = FacePlane(i);
for(int j = 0; j < (int)face.v.size(); ++j) // O(1)
if (facePlane.Distance(v[face.v[j]]) > epsilon)
return false;
}
}
return true;
}
int Polyhedron::NearestVertex(const vec &point) const
{
int nearest = -1;
float nearestDistSq = FLOAT_INF;
for(int i = 0; i < (int)v.size(); ++i)
{
float dSq = point.DistanceSq(v[i]);
if (dSq < nearestDistSq)
{
nearestDistSq = dSq;
nearest = i;
}
}
return nearest;
}
float Polyhedron::FaceContainmentDistance2D(int faceIndex, const vec &worldSpacePoint, float polygonThickness) const
{
// N.B. This implementation is a duplicate of Polygon::Contains, but adapted to avoid dynamic memory allocation
// related to converting the face of a Polyhedron to a Polygon object.
// Implementation based on the description from http://erich.realtimerendering.com/ptinpoly/
const Face &face = f[faceIndex];
const std::vector<int> &vertices = face.v;
if (vertices.size() < 3)
return -FLOAT_INF; // Certainly not intersecting, so return -inf denoting "strongly not contained"
Plane p = FacePlane(faceIndex);
if (FacePlane(faceIndex).Distance(worldSpacePoint) > polygonThickness)
return -FLOAT_INF;
int numIntersections = 0;
vec basisU = (vec)v[vertices[1]] - (vec)v[vertices[0]];
basisU.Normalize();
vec basisV = Cross(p.normal, basisU).Normalized();
mathassert(basisU.IsNormalized());
mathassert(basisV.IsNormalized());
mathassert(basisU.IsPerpendicular(basisV));
mathassert(basisU.IsPerpendicular(p.normal));
mathassert(basisV.IsPerpendicular(p.normal));
// Tracks a pseudo-distance of the point to the ~nearest edge of the polygon. If the point is very close to the polygon
// edge, this is very small, and it's possible that due to numerical imprecision we cannot rely on the result in higher-level
// algorithms that invoke this function.
float faceContainmentDistance = FLOAT_INF;
const float epsilon = 1e-4f;
vec vt = vec(v[vertices.back()]) - worldSpacePoint;
float2 p0 = float2(Dot(vt, basisU), Dot(vt, basisV));
if (Abs(p0.y) < epsilon)
p0.y = -epsilon; // Robustness check - if the ray (0,0) -> (+inf, 0) would pass through a vertex, move the vertex slightly.
for(size_t i = 0; i < vertices.size(); ++i)
{
vt = vec(v[vertices[i]]) - worldSpacePoint;
float2 p1 = float2(Dot(vt, basisU), Dot(vt, basisV));
if (Abs(p1.y) < epsilon)
p1.y = -epsilon; // Robustness check - if the ray (0,0) -> (+inf, 0) would pass through a vertex, move the vertex slightly.
if (p0.y * p1.y < 0.f)
{
float minX = Min(p0.x, p1.x);
if (minX > 0.f)
{
faceContainmentDistance = Min(faceContainmentDistance, minX);
++numIntersections;
}
else if (Max(p0.x, p1.x) > 0.f)
{
// P = p0 + t*(p1-p0) == (x,0)
// p0.x + t*(p1.x-p0.x) == x
// p0.y + t*(p1.y-p0.y) == 0
// t == -p0.y / (p1.y - p0.y)
// Test whether the lines (0,0) -> (+inf,0) and p0 -> p1 intersect at a positive X-coordinate.
float2 d = p1 - p0;
if (d.y != 0.f)
{
float t = -p0.y / d.y;
float x = p0.x + t * d.x;
if (t >= 0.f && t <= 1.f)
{
// Remember how close the point was to the edge, for tracking robustness/goodness of the result.
// If this is very large, then we can conclude that the point was contained or not contained in the face.
faceContainmentDistance = Min(faceContainmentDistance, Abs(x));
if (x >= 0.f)
++numIntersections;
}
}
}
}
p0 = p1;
}
// Positive return value: face contains the point. Negative: face did not contain the point.
return (numIntersections % 2 == 1) ? faceContainmentDistance : -faceContainmentDistance;
}
bool Polyhedron::FaceContains(int faceIndex, const vec &worldSpacePoint, float polygonThickness) const
{
float faceContainmentDistance = FaceContainmentDistance2D(faceIndex, worldSpacePoint, polygonThickness);
return faceContainmentDistance >= 0.f;
}
bool Polyhedron::Contains(const vec &point) const
{
if (v.size() <= 3)
{
if (v.size() == 3)
return Triangle(vec(v[0]), vec(v[1]), vec(v[2])).Contains(point);
else if (v.size() == 2)
return LineSegment(vec(v[0]), vec(v[1])).Contains(point);
else if (v.size() == 1)
return vec(v[0]).Equals(point);
else
return false;
}
int bestNumIntersections = 0;
float bestFaceContainmentDistance = 0.f;
// General strategy: pick a ray from the query point to a random direction, and count the number of times the ray intersects
// a face. If it intersects an odd number of times, the given point must have been inside the polyhedron.
// But unfortunately for numerical stability, we must be smart with the choice of the ray direction. If we pick a ray direction
// which exits the polyhedron precisely at a vertex, or at an edge of two adjoining faces, we might count those twice. Therefore
// try to pick a ray direction that passes safely through a center of some face. If we detect that there was a tricky face that
// the ray passed too close to an edge, we have no choice but to pick another ray direction and hope that it passes through
// the polyhedron in a safer manner.
// Loop through each face to choose the ray direction. If our choice was good, we only do this once and the algorithm can exit
// after the first iteration at j == 0. If not, we iterate more faces of the polyhedron to try to find one that is safe for
// ray-polyhedron examination.
for(int j = 0; j < (int)f.size(); ++j)
{
if (f[j].v.size() < 3)
continue;
// Accumulate how many times the ray intersected a face of the polyhedron.
int numIntersections = 0;
// Track a pseudo-distance of the closest edge of a face that the ray passed through. If this distance ends up being too
// small, we decide to not trust the result we got, and proceed to another iteration of j, hoping to guess a better-behaving
// direction for the test ray.
float faceContainmentDistance = FLOAT_INF;
vec dir = ((vec)v[f[j].v[0]] + (vec)v[f[j].v[1]] + (vec)v[f[j].v[2]]) * 0.33333333333f - point;
#ifdef MATH_VEC_IS_FLOAT4
dir.w = 0.f;
#endif
if (dir.Normalize() <= 0.f)
continue;
Ray r(POINT_VEC_SCALAR(0.f), dir);
for(int i = 0; i < (int)f.size(); ++i)
{
Plane p((vec)v[f[i].v[0]] - point, (vec)v[f[i].v[1]] - point, (vec)v[f[i].v[2]] - point);
float d;
// Find the intersection of the plane and the ray.
if (p.Intersects(r, &d))
{
float containmentDistance2D = FaceContainmentDistance2D(i, r.GetPoint(d) + point);
if (containmentDistance2D >= 0.f)
++numIntersections;
faceContainmentDistance = Min(faceContainmentDistance, Abs(containmentDistance2D));
}
}
if (faceContainmentDistance > 1e-2f) // The nearest edge was far enough, we conclude the result is believable.
return (numIntersections % 2) == 1;
else if (faceContainmentDistance >= bestFaceContainmentDistance)
{
// The ray passed too close to a face edge. Remember this result, but proceed to another test iteration to see if we can
// find a more plausible test ray.
bestNumIntersections = numIntersections;
bestFaceContainmentDistance = faceContainmentDistance;
}
}
// We tested rays through each face of the polyhedron, but all rays passed too close to edges of the polyhedron faces. Return
// the result from the test that was farthest to any of the face edges.
return (bestNumIntersections % 2) == 1;
}
bool Polyhedron::Contains(const LineSegment &lineSegment) const
{
return Contains(lineSegment.a) && Contains(lineSegment.b);
}
bool Polyhedron::Contains(const Triangle &triangle) const
{
return Contains(triangle.a) && Contains(triangle.b) && Contains(triangle.c);
}
bool Polyhedron::Contains(const Polygon &polygon) const
{
for(int i = 0; i < polygon.NumVertices(); ++i)
if (!Contains(polygon.Vertex(i)))
return false;
return true;
}
bool Polyhedron::Contains(const AABB &aabb) const
{
for(int i = 0; i < 8; ++i)
if (!Contains(aabb.CornerPoint(i)))
return false;
return true;
}
bool Polyhedron::Contains(const OBB &obb) const
{
for(int i = 0; i < 8; ++i)
if (!Contains(obb.CornerPoint(i)))
return false;
return true;
}
bool Polyhedron::Contains(const Frustum &frustum) const
{
for(int i = 0; i < 8; ++i)
if (!Contains(frustum.CornerPoint(i)))
return false;
return true;
}
bool Polyhedron::Contains(const Polyhedron &polyhedron) const
{
assume(polyhedron.IsClosed());
for(int i = 0; i < polyhedron.NumVertices(); ++i)
if (!Contains(polyhedron.Vertex(i)))
return false;
return true;
}
bool Polyhedron::ContainsConvex(const vec &point, float epsilon) const
{
assume(IsConvex());
for(int i = 0; i < NumFaces(); ++i)
if (FacePlane(i).SignedDistance(point) > epsilon)
return false;
return true;
}
bool Polyhedron::ContainsConvex(const LineSegment &lineSegment) const
{
return ContainsConvex(lineSegment.a) && ContainsConvex(lineSegment.b);
}
bool Polyhedron::ContainsConvex(const Triangle &triangle) const
{
return ContainsConvex(triangle.a) && ContainsConvex(triangle.b) && ContainsConvex(triangle.c);
}
vec Polyhedron::ClosestPointConvex(const vec &point) const
{
assume(IsConvex());
if (ContainsConvex(point))
return point;
vec closestPoint = vec::nan;
float closestDistance = FLT_MAX;
for(int i = 0; i < NumFaces(); ++i)
{
vec closestOnPoly = FacePolygon(i).ClosestPoint(point);
float d = closestOnPoly.DistanceSq(point);
if (d < closestDistance)
{
closestPoint = closestOnPoly;
closestDistance = d;
}
}
return closestPoint;
}