forked from PixarAnimationStudios/OpenUSD
-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathfrustum.cpp
1343 lines (1158 loc) · 45.8 KB
/
frustum.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 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#include "pxr/pxr.h"
#include "pxr/base/gf/frustum.h"
#include "pxr/base/gf/bbox3d.h"
#include "pxr/base/gf/matrix4d.h"
#include "pxr/base/gf/ostreamHelpers.h"
#include "pxr/base/gf/plane.h"
#include "pxr/base/gf/vec2d.h"
#include "pxr/base/gf/vec2f.h"
#include "pxr/base/gf/math.h"
#include "pxr/base/tf/enum.h"
#include "pxr/base/tf/type.h"
#include <algorithm>
#include <iostream>
using namespace std;
PXR_NAMESPACE_OPEN_SCOPE
// CODE_COVERAGE_OFF_GCOV_BUG
TF_REGISTRY_FUNCTION(TfType) {
TfType::Define<GfFrustum>();
}
// CODE_COVERAGE_ON_GCOV_BUG
TF_REGISTRY_FUNCTION(TfEnum) {
TF_ADD_ENUM_NAME(GfFrustum::Orthographic);
TF_ADD_ENUM_NAME(GfFrustum::Perspective);
}
GfFrustum::GfFrustum() :
_position(0),
_window(GfVec2d(-1.0, -1.0), GfVec2d(1.0, 1.0)),
_nearFar(1.0, 10.0),
_viewDistance(5.0),
_projectionType(GfFrustum::Perspective)
{
_rotation.SetIdentity();
}
GfFrustum::GfFrustum(const GfVec3d &position, const GfRotation &rotation,
const GfRange2d &window, const GfRange1d &nearFar,
GfFrustum::ProjectionType projectionType,
double viewDistance) :
_position(position),
_rotation(rotation),
_window(window),
_nearFar(nearFar),
_viewDistance(viewDistance),
_projectionType(projectionType)
{
}
GfFrustum::GfFrustum(const GfMatrix4d &camToWorldXf,
const GfRange2d &window, const GfRange1d &nearFar,
GfFrustum::ProjectionType projectionType,
double viewDistance) :
_window(window),
_nearFar(nearFar),
_viewDistance(viewDistance),
_projectionType(projectionType)
{
SetPositionAndRotationFromMatrix(camToWorldXf);
}
GfFrustum::~GfFrustum()
{
}
void
GfFrustum::SetPerspective(double fieldOfViewHeight, double aspectRatio,
double nearDistance, double farDistance)
{
SetPerspective(fieldOfViewHeight, true, aspectRatio,
nearDistance, farDistance);
}
void
GfFrustum::SetPerspective(double fieldOfView, bool isFovVertical,
double aspectRatio,
double nearDistance, double farDistance)
{
_projectionType = GfFrustum::Perspective;
double yDist = 1.0;
double xDist = 1.0;
// Check for 0, use 1 in that case
if (aspectRatio == 0.0) {
aspectRatio = 1.0;
}
if (isFovVertical) {
// vertical is taken from the given field of view
yDist = tan(GfDegreesToRadians(fieldOfView / 2.0))
* GetReferencePlaneDepth();
// horizontal is determined by aspect ratio
xDist = yDist * aspectRatio;
} else {
// horizontal is taken from the given field of view
xDist = tan(GfDegreesToRadians(fieldOfView / 2.0))
* GetReferencePlaneDepth();
// vertical is determined by aspect ratio
yDist = xDist / aspectRatio;
}
_window.SetMin(GfVec2d(-xDist, -yDist));
_window.SetMax(GfVec2d(xDist, yDist));
_nearFar.SetMin(nearDistance);
_nearFar.SetMax(farDistance);
_DirtyFrustumPlanes();
}
bool
GfFrustum::GetPerspective(double *fieldOfViewHeight, double *aspectRatio,
double *nearDistance, double *farDistance) const
{
return GetPerspective(true, fieldOfViewHeight, aspectRatio,
nearDistance, farDistance);
}
bool
GfFrustum::GetPerspective(bool isFovVertical,
double *fieldOfView, double *aspectRatio,
double *nearDistance, double *farDistance) const
{
if (_projectionType != GfFrustum::Perspective)
return false;
GfVec2d winSize = _window.GetSize();
if (isFovVertical) {
*fieldOfView =
2.0 * GfRadiansToDegrees( atan(winSize[1] / 2.0)
/ GetReferencePlaneDepth() );
} else {
*fieldOfView =
2.0 * GfRadiansToDegrees( atan(winSize[0] / 2.0)
/ GetReferencePlaneDepth() );
}
*aspectRatio = winSize[0] / winSize[1];
*nearDistance = _nearFar.GetMin();
*farDistance = _nearFar.GetMax();
return true;
}
double
GfFrustum::GetFOV(bool isFovVertical /* = false */)
{
double result = 0.0;
if (GetProjectionType() == GfFrustum::Perspective) {
double aspectRatio;
double nearDistance;
double farDistance;
GetPerspective(isFovVertical,
&result,
&aspectRatio,
&nearDistance,
&farDistance);
}
return result;
}
void
GfFrustum::SetOrthographic(double left, double right,
double bottom, double top,
double nearPlane, double farPlane)
{
_projectionType = GfFrustum::Orthographic;
_window.SetMin(GfVec2d(left, bottom));
_window.SetMax(GfVec2d(right, top));
_nearFar.SetMin(nearPlane);
_nearFar.SetMax(farPlane);
_DirtyFrustumPlanes();
}
bool
GfFrustum::GetOrthographic(double *left, double *right,
double *bottom, double *top,
double *nearPlane, double *farPlane) const
{
if (_projectionType != GfFrustum::Orthographic)
return false;
*left = _window.GetMin()[0];
*right = _window.GetMax()[0];
*bottom = _window.GetMin()[1];
*top = _window.GetMax()[1];
*nearPlane = _nearFar.GetMin();
*farPlane = _nearFar.GetMax();
return true;
}
void
GfFrustum::FitToSphere(const GfVec3d ¢er, double radius, double slack)
{
//
// The first part of this computes a good value for
// _viewDistance and modifies the side (left, right, bottom,
// and top) coordinates of the frustum as necessary.
//
if (_projectionType == GfFrustum::Orthographic) {
// Set the distance so the viewpoint is outside the sphere.
_viewDistance = radius + slack;
// Set the camera window to enclose the sphere.
_window = GfRange2d(GfVec2d(-radius, -radius),
GfVec2d(radius, radius));
}
else {
// Find the plane coordinate to use to compute the view.
// Assuming symmetry, it should be the half-size of the
// smaller of the two viewing angles. If asymmetric in a
// dimension, use the larger size in that dimension.
size_t whichDim = ComputeAspectRatio() > 1.0 ? 1 : 0;
// XXX-doc
double min = _window.GetMin()[whichDim];
double max = _window.GetMax()[whichDim];
double halfSize;
if (min > 0.0) {
halfSize = max;
} else if (max < 0.0) {
// CODE_COVERAGE_OFF_GCOV_BUG - seems to be hit but gcov disagrees
halfSize = min;
// CODE_COVERAGE_ON_GCOV_BUG
} else if (-min > max) {
halfSize = min;
} else {
halfSize = max;
}
if (halfSize < 0.0) {
halfSize = -halfSize;
} else if (halfSize == 0.0) {
halfSize = 1.0; // Why not?
}
// Determine the distance of the viewpoint from the center of
// the sphere to make the frustum tangent to the sphere. Use
// similar triangles: the right triangle formed by the
// viewpoint and the half-size on the plane is similar to the
// right triangle formed by the viewpoint and the radius of
// the sphere at the point of tangency.
_viewDistance =
radius * (1.0/halfSize) *
sqrt(GfSqr(halfSize) + GfSqr(_nearFar.GetMin()));
// XXX.
// Hmmm. This is not really used anywhere but in tests, so
// not gonna fix right now but it seems to me the above equation is
// off.
// In the diagram below, similar triangles yield the following
// equal ratios:
// halfSize / referencePlaneDepth = radius / tanDist
// So tanDist = (radius * referencePlaneDepth) / halfSize
// Then, because it's a right triangle:
// viewDistance = sqrt( GfSqr(radius) + GfSqr(tanDist))
/*
----- |\ /
^ | \ ra /
| | \ di /
| | \ us /
| | \ /
| | \ /
| | \/ <---- make believe this is a right angle
| |------------/ ------
| | / ^
| | / |
viewDistance | / |
| | / |
| | /t |
| | /s referencePlaneDepth
| | /i |
| | /d |
| | /n |
| | /a |
| | /t v
v |/ ------
------
| |
|<-halfSize->|
| |
| |
*/
}
// Adjust the camera so the near plane touches the sphere and the
// far plane encloses the sphere.
_nearFar.SetMin(_viewDistance - (radius + slack));
_nearFar.SetMax(_nearFar.GetMin() + 2.0 * (radius + slack));
// Set the camera to use the new position. The view direction
// should not have changed.
_position = center - _viewDistance * ComputeViewDirection();
}
GfFrustum &
GfFrustum::Transform(const GfMatrix4d &matrix)
{
// We'll need the old parameters as we build up the new ones, so, work
// on a newly instantiated frustum. We'll replace the contents of
// this frustum with it once we are done. Note that _dirty is true
// by default, so, there is no need to initialize it here.
GfFrustum frustum;
// Copy the projection type
frustum._projectionType = _projectionType;
// Transform the position of the frustum
frustum._position = matrix.Transform(_position);
// Transform the rotation as follows:
// 1. build view and direction vectors
// 2. transform them with the given matrix
// 3. normalize the vectors and cross them to build an orthonormal frame
// 4. construct a rotation matrix
// 5. extract the new rotation from the matrix
// Generate view direction and up vector
GfVec3d viewDir = ComputeViewDirection();
GfVec3d upVec = ComputeUpVector();
// Transform by matrix
GfVec3d viewDirPrime = matrix.TransformDir(viewDir);
GfVec3d upVecPrime = matrix.TransformDir(upVec);
// Normalize. Save the vec size since it will be used to scale near/far.
double scale = viewDirPrime.Normalize();
upVecPrime.Normalize();
// Cross them to get the third axis. Voila. We have an orthonormal frame.
GfVec3d viewRightPrime = GfCross(viewDirPrime, upVecPrime);
viewRightPrime.Normalize();
// Construct a rotation matrix using the axes.
//
// [ right 0 ]
// [ up 1 ]
// [ -viewDir 0 ]
// [ 0 0 0 1 ]
GfMatrix4d rotMatrix;
rotMatrix.SetIdentity();
// first row
rotMatrix[0][0] = viewRightPrime[0];
rotMatrix[0][1] = viewRightPrime[1];
rotMatrix[0][2] = viewRightPrime[2];
// second row
rotMatrix[1][0] = upVecPrime[0];
rotMatrix[1][1] = upVecPrime[1];
rotMatrix[1][2] = upVecPrime[2];
// third row
rotMatrix[2][0] = -viewDirPrime[0];
rotMatrix[2][1] = -viewDirPrime[1];
rotMatrix[2][2] = -viewDirPrime[2];
// Extract rotation
frustum._rotation = rotMatrix.ExtractRotation();
// Since we applied the matrix to the direction vector, we can use
// its length to find out the scaling that needs to applied to the
// near and far plane.
frustum._nearFar = _nearFar * scale;
// Use the same length to scale the view distance
frustum._viewDistance = _viewDistance * scale;
// Transform the reference plane as follows:
//
// - construct two 3D points that are on the reference plane
// (left/bottom and right/top corner of the reference window)
// - transform the points with the given matrix
// - move the window back to one unit from the viewpoint and
// extract the 2D coordinates that would form the new reference
// window
//
// A note on how we do the last "move" of the reference window:
// Using similar triangles and the fact that the reference window
// is one unit away from the viewpoint, one can show that it's
// sufficient to divide the x and y components of the transformed
// corners by the length of the transformed direction vector.
//
// A 2D diagram helps:
//
// |
// |
// | |
// * ------+------------+
// vp |y1 |
// |
// \--d1--/ |y2
//
// \-------d2----------/
//
// So, y1/y2 = d1/d2 ==> y1 = y2 * d1/d2
// Since d1 = 1 ==> y1 = y2 / d2
// The same argument applies to the x coordinate.
//
// NOTE: In an orthographic projection, the last step (division by
// the length of the vector) is skipped.
//
// XXX NOTE2: The above derivation relies on the
// fact that GetReferecePlaneDepth() is 1.0.
// If we ever allow this to NOT be 1, we'll need to fix this up.
const GfVec2d &min = _window.GetMin();
const GfVec2d &max = _window.GetMax();
// Construct the corner points in 3D as follows: construct a starting
// point by using the x and y coordinates of the reference plane and
// -1 as the z coordinate. Add the position of the frustum to generate
// the actual points in world-space coordinates.
GfVec3d leftBottom =
_position + _rotation.TransformDir(GfVec3d(min[0], min[1], -1.0));
GfVec3d rightTop =
_position + _rotation.TransformDir(GfVec3d(max[0], max[1], -1.0));
// Now, transform the corner points by the given matrix
leftBottom = matrix.Transform(leftBottom);
rightTop = matrix.Transform(rightTop);
// Subtract the transformed frustum position from the transformed
// corner points. Then, rotate the points using the rotation that would
// transform the view direction vector back to (0, 0, -1). This brings
// the corner points from the woorld coordinate system into the local
// frustum one.
leftBottom -= frustum._position;
rightTop -= frustum._position;
leftBottom = frustum._rotation.GetInverse().TransformDir(leftBottom);
rightTop = frustum._rotation.GetInverse().TransformDir(rightTop);
// Finally, use the similar triangles trick to bring the corner
// points back at one unit away from the point. These scaled x and
// y coordinates can be directly used to construct the new
// transformed reference plane. Skip the scaling step for an
// orthographic projection, though.
if (_projectionType == Perspective) {
leftBottom /= scale;
rightTop /= scale;
}
frustum._window.SetMin(GfVec2d(leftBottom[0], leftBottom[1]));
frustum._window.SetMax(GfVec2d(rightTop[0], rightTop[1]));
// Note that negative scales in the transform have the potential
// to flip the window. Fix it if necessary.
GfVec2d wMin = frustum._window.GetMin();
GfVec2d wMax = frustum._window.GetMax();
// Make sure left < right
if ( wMin[0] > wMax[0] ) {
std::swap( wMin[0], wMax[0] );
}
// Make sure bottom < top
if ( wMin[1] > wMax[1] ) {
std::swap( wMin[1], wMax[1] );
}
frustum._window.SetMin( wMin );
frustum._window.SetMax( wMax );
*this = frustum;
return *this;
}
GfVec3d
GfFrustum::ComputeViewDirection() const
{
return _rotation.TransformDir(-GfVec3d::ZAxis());
}
GfVec3d
GfFrustum::ComputeUpVector() const
{
return _rotation.TransformDir(GfVec3d::YAxis());
}
void
GfFrustum::ComputeViewFrame(GfVec3d *side,
GfVec3d *up,
GfVec3d *view) const
{
*up = ComputeUpVector();
*view = ComputeViewDirection();
*side = GfCross(*view, *up);
}
GfVec3d
GfFrustum::ComputeLookAtPoint() const
{
return _position + _viewDistance * ComputeViewDirection();
}
GfMatrix4d
GfFrustum::ComputeViewMatrix() const
{
GfMatrix4d m;
m.SetLookAt(_position, _rotation);
return m;
}
GfMatrix4d
GfFrustum::ComputeViewInverse() const
{
return ComputeViewMatrix().GetInverse();
}
GfMatrix4d
GfFrustum::ComputeProjectionMatrix() const
{
// Build the projection matrix per Section 2.11 of
// The OpenGL Specification: Coordinate Transforms.
GfMatrix4d matrix;
matrix.SetIdentity();
const double l = _window.GetMin()[0];
const double r = _window.GetMax()[0];
const double b = _window.GetMin()[1];
const double t = _window.GetMax()[1];
const double n = _nearFar.GetMin();
const double f = _nearFar.GetMax();
const double rl = r - l;
const double tb = t - b;
const double fn = f - n;
if (_projectionType == GfFrustum::Orthographic) {
matrix[0][0] = 2.0 / rl;
matrix[1][1] = 2.0 / tb;
matrix[2][2] = -2.0 / fn;
matrix[3][0] = -(r + l) / rl;
matrix[3][1] = -(t + b) / tb;
matrix[3][2] = -(f + n) / fn;
}
else {
// Perspective:
// The window coordinates are specified with respect to the
// reference plane (near == 1).
// XXX Note: If we ever allow reference plane depth to be other
// than 1.0, we'll need to revisit this.
matrix[0][0] = 2.0 / rl;
matrix[1][1] = 2.0 / tb;
matrix[2][2] = -(f + n) / fn;
matrix[2][0] = (r + l) / rl;
matrix[2][1] = (t + b) / tb;
matrix[3][2] = -2.0 * n * f / fn;
matrix[2][3] = -1.0;
matrix[3][3] = 0.0;
}
return matrix;
}
double
GfFrustum::ComputeAspectRatio() const
{
GfVec2d winSize = _window.GetSize();
double aspectRatio = 0.0;
if (winSize[1] != 0.0)
// Negative winsize is used for envcubes, believe it or not.
aspectRatio = fabs(winSize[0] / winSize[1]);
return aspectRatio;
}
vector<GfVec3d>
GfFrustum::ComputeCorners() const
{
const GfVec2d &winMin = _window.GetMin();
const GfVec2d &winMax = _window.GetMax();
double near = _nearFar.GetMin();
double far = _nearFar.GetMax();
vector<GfVec3d> corners;
corners.reserve(8);
if (_projectionType == Perspective) {
// Compute the eye-space corners of the near-plane and
// far-plane frustum rectangles using similar triangles. The
// reference plane in which the window rectangle is defined is
// a distance of 1 from the eyepoint. By similar triangles,
// just multiply the window points by near and far to get the
// near and far rectangles.
// XXX Note: If we ever allow reference plane depth to be other
// than 1.0, we'll need to revisit this.
corners.push_back(GfVec3d(near * winMin[0], near * winMin[1], -near));
corners.push_back(GfVec3d(near * winMax[0], near * winMin[1], -near));
corners.push_back(GfVec3d(near * winMin[0], near * winMax[1], -near));
corners.push_back(GfVec3d(near * winMax[0], near * winMax[1], -near));
corners.push_back(GfVec3d(far * winMin[0], far * winMin[1], -far));
corners.push_back(GfVec3d(far * winMax[0], far * winMin[1], -far));
corners.push_back(GfVec3d(far * winMin[0], far * winMax[1], -far));
corners.push_back(GfVec3d(far * winMax[0], far * winMax[1], -far));
}
else {
// Just use the reference plane rectangle as is, translated to
// the near and far planes.
corners.push_back(GfVec3d(winMin[0], winMin[1], -near));
corners.push_back(GfVec3d(winMax[0], winMin[1], -near));
corners.push_back(GfVec3d(winMin[0], winMax[1], -near));
corners.push_back(GfVec3d(winMax[0], winMax[1], -near));
corners.push_back(GfVec3d(winMin[0], winMin[1], -far));
corners.push_back(GfVec3d(winMax[0], winMin[1], -far));
corners.push_back(GfVec3d(winMin[0], winMax[1], -far));
corners.push_back(GfVec3d(winMax[0], winMax[1], -far));
}
// Each corner is then transformed into world space by the inverse
// of the view matrix.
GfMatrix4d m = ComputeViewInverse();
for (int i = 0; i < 8; i++)
corners[i] = m.Transform(corners[i]);
return corners;
}
vector<GfVec3d>
GfFrustum::ComputeCornersAtDistance(double d) const
{
const GfVec2d &winMin = _window.GetMin();
const GfVec2d &winMax = _window.GetMax();
vector<GfVec3d> corners;
corners.reserve(4);
if (_projectionType == Perspective) {
// Similar to ComputeCorners
corners.push_back(GfVec3d(d * winMin[0], d * winMin[1], -d));
corners.push_back(GfVec3d(d * winMax[0], d * winMin[1], -d));
corners.push_back(GfVec3d(d * winMin[0], d * winMax[1], -d));
corners.push_back(GfVec3d(d * winMax[0], d * winMax[1], -d));
}
else {
corners.push_back(GfVec3d(winMin[0], winMin[1], -d));
corners.push_back(GfVec3d(winMax[0], winMin[1], -d));
corners.push_back(GfVec3d(winMin[0], winMax[1], -d));
corners.push_back(GfVec3d(winMax[0], winMax[1], -d));
}
// Each corner is then transformed into world space by the inverse
// of the view matrix.
const GfMatrix4d m = ComputeViewInverse();
for (int i = 0; i < 4; i++)
corners[i] = m.Transform(corners[i]);
return corners;
}
GfFrustum
GfFrustum::ComputeNarrowedFrustum(const GfVec2d &point,
const GfVec2d &halfSize) const
{
// Map the point from normalized space (-1 to 1) onto the frustum's
// window. First, convert the point into the range from 0 to 1,
// then interpolate in the window rectangle.
GfVec2d scaledPoint = .5 * (GfVec2d(1.0, 1.0) + point);
GfVec2d windowPoint = _window.GetMin() + GfCompMult(scaledPoint,
_window.GetSize());
return _ComputeNarrowedFrustumSub(windowPoint, halfSize);
}
GfFrustum
GfFrustum::ComputeNarrowedFrustum(const GfVec3d &worldPoint,
const GfVec2d &halfSize) const
{
// Map the point from worldspace onto the frustum's window
GfVec3d lclPt = ComputeViewMatrix().Transform(worldPoint);
if (lclPt[2] >= 0) {
TF_WARN("Given worldPoint is behind or at the eye");
// Start with this frustum
return *this;
}
double scaleFactor = _nearFar.GetMin() / -lclPt[2];
GfVec2d windowPoint(lclPt[0] * scaleFactor, lclPt[1] * scaleFactor);
return _ComputeNarrowedFrustumSub(windowPoint, halfSize);
}
GfFrustum
GfFrustum::_ComputeNarrowedFrustumSub(const GfVec2d windowPoint,
const GfVec2d &halfSize) const
{
// Start with this frustum
GfFrustum narrowedFrustum = *this;
// Also convert the sizes.
GfVec2d halfSizeOnRefPlane = .5 * GfCompMult(halfSize, _window.GetSize());
// Shrink the narrowed frustum's window to surround the point.
GfVec2d min = windowPoint - halfSizeOnRefPlane;
GfVec2d max = windowPoint + halfSizeOnRefPlane;
// Make sure the new bounds are within the old window.
if (min[0] < _window.GetMin()[0])
min[0] = _window.GetMin()[0];
if (min[1] < _window.GetMin()[1])
min[1] = _window.GetMin()[1];
if (max[0] > _window.GetMax()[0])
max[0] = _window.GetMax()[0];
if (max[1] > _window.GetMax()[1])
max[1] = _window.GetMax()[1];
// Set the window to the result.
narrowedFrustum.SetWindow(GfRange2d(min, max));
return narrowedFrustum;
}
// Utility function for mapping an input value from
// one range to another.
static double
_Rescale(double in,
double inA, double inB,
double outA, double outB )
{
double factor = (inA==inB) ? 0.0 : ((inA-in) / (inA-inB));
return outA + ((outB-outA)*factor);
}
static GfRay _ComputeUntransformedRay(GfFrustum::ProjectionType projectionType,
const GfRange2d &window,
const GfVec2d &windowPos)
{
// Compute position on window, from provided normalized
// (-1 to 1) coordinates.
double winX = _Rescale(windowPos[0], -1.0, 1.0,
window.GetMin()[0], window.GetMax()[0]);
double winY = _Rescale(windowPos[1], -1.0, 1.0,
window.GetMin()[1], window.GetMax()[1]);
// Compute the camera-space starting point (the viewpoint) and
// direction (toward the point on the window).
GfVec3d pos;
GfVec3d dir;
if (projectionType == GfFrustum::Perspective) {
pos = GfVec3d(0);
dir = GfVec3d(winX, winY, -1.0).GetNormalized();
}
else {
pos.Set(winX, winY, 0.0);
dir = -GfVec3d::ZAxis();
}
// Build and return the ray
return GfRay(pos, dir);
}
GfRay
GfFrustum::ComputeRay(const GfVec2d &windowPos) const
{
GfRay ray = _ComputeUntransformedRay(_projectionType, _window, windowPos);
// Transform these by the inverse of the view matrix.
const GfMatrix4d &viewInverse = ComputeViewInverse();
GfVec3d rayFrom = viewInverse.Transform(ray.GetStartPoint());
GfVec3d rayDir = viewInverse.TransformDir(ray.GetDirection());
// Build and return the ray
return GfRay(rayFrom, rayDir);
}
GfRay
GfFrustum::ComputePickRay(const GfVec2d &windowPos) const
{
GfRay ray = _ComputeUntransformedRay(_projectionType, _window, windowPos);
return _ComputePickRayOffsetToNearPlane(ray.GetStartPoint(),
ray.GetDirection());
}
GfRay
GfFrustum::ComputeRay(const GfVec3d &worldSpacePos) const
{
GfVec3d camSpaceToPos = ComputeViewMatrix().Transform(worldSpacePos);
// Compute the camera-space starting point (the viewpoint) and
// direction (toward the point camSpaceToPos).
GfVec3d pos;
GfVec3d dir;
if (_projectionType == Perspective) {
pos = GfVec3d(0);
dir = camSpaceToPos.GetNormalized();
}
else {
pos.Set(camSpaceToPos[0], camSpaceToPos[1], 0.0);
dir = -GfVec3d::ZAxis();
}
// Transform these by the inverse of the view matrix.
const GfMatrix4d &viewInverse = ComputeViewInverse();
GfVec3d rayFrom = viewInverse.Transform(pos);
GfVec3d rayDir = viewInverse.TransformDir(dir);
// Build and return the ray
return GfRay(rayFrom, rayDir);
}
GfRay
GfFrustum::ComputePickRay(const GfVec3d &worldSpacePos) const
{
GfVec3d camSpaceToPos = ComputeViewMatrix().Transform(worldSpacePos);
// Compute the camera-space starting point (the viewpoint) and
// direction (toward the point camSpaceToPos).
GfVec3d pos;
GfVec3d dir;
if (_projectionType == Perspective) {
pos = GfVec3d(0);
dir = camSpaceToPos.GetNormalized();
}
else {
pos.Set(camSpaceToPos[0], camSpaceToPos[1], 0.0);
dir = -GfVec3d::ZAxis();
}
return _ComputePickRayOffsetToNearPlane(pos, dir);
}
GfRay
GfFrustum::_ComputePickRayOffsetToNearPlane(const GfVec3d &camSpaceFrom,
const GfVec3d &camSpaceDir) const
{
// Move the starting point to the near plane so we don't pick
// anything that's clipped out of view.
GfVec3d rayFrom = camSpaceFrom + _nearFar.GetMin() * camSpaceDir;
// Transform these by the inverse of the view matrix.
const GfMatrix4d &viewInverse = ComputeViewInverse();
rayFrom = viewInverse.Transform(rayFrom);
GfVec3d rayDir = viewInverse.TransformDir(camSpaceDir);
// Build and return the ray
return GfRay(rayFrom, rayDir);
}
bool
GfFrustum::Intersects(const GfBBox3d &bbox) const
{
if (bbox.GetBox().IsEmpty())
return false;
// Recalculate frustum planes if necessary
_CalculateFrustumPlanes();
// Get the bbox in its local space and the matrix that converts
// world space to that local space.
const GfRange3d &localBBox = bbox.GetRange();
const GfMatrix4d &worldToLocal = bbox.GetInverseMatrix();
// Test the bbox against each of the frustum planes, transforming
// the plane by the inverse of the matrix to bring it into the
// bbox's local space.
for (size_t i = 0; i < _planes.size(); i++) {
GfPlane localPlane = _planes[i];
localPlane.Transform(worldToLocal);
if (! localPlane.IntersectsPositiveHalfSpace(localBBox))
return false;
}
return true;
}
bool
GfFrustum::Intersects(const GfVec3d &point) const
{
// Recalculate frustum planes if necessary
_CalculateFrustumPlanes();
// Determine if the point is inside/intersecting the frustum. Quit early
// if the point is outside of any of the frustum planes.
for (size_t i = 0; i < _planes.size(); i++) {
if (!_planes[i].IntersectsPositiveHalfSpace(point)) {
return false;
}
}
return true;
}
inline static uint32_t
_CalcIntersectionBitMask( const std::vector<GfPlane> & planes,
GfVec3d const &p)
{
return
(1 << 0) * planes[0].IntersectsPositiveHalfSpace(p) +
(1 << 1) * planes[1].IntersectsPositiveHalfSpace(p) +
(1 << 2) * planes[2].IntersectsPositiveHalfSpace(p) +
(1 << 3) * planes[3].IntersectsPositiveHalfSpace(p) +
(1 << 4) * planes[4].IntersectsPositiveHalfSpace(p) +
(1 << 5) * planes[5].IntersectsPositiveHalfSpace(p);
}
bool
GfFrustum::_SegmentIntersects(GfVec3d const &p0, uint32_t p0Mask,
GfVec3d const &p1, uint32_t p1Mask) const
{
// If any of the 6 bits is 0 in both masks, then both points are
// on the bad side of the corresponding plane. This means that
// there can't be any intersection.
if ((p0Mask | p1Mask) != 0x3F)
return false;
// If either of the masks has all 6 planes set, the point is
// inside the frustum, so there's an intersection.
if ((p0Mask == 0x3F) || (p1Mask == 0x3F))
return true;
// If we get here, the 2 points of the segment are both outside
// the frustum, but not both on the outside of any single plane.
// Now we can clip the segment against each plane that it
// straddles to see if the resulting segment has any length.
// Perform the clipping using parametric coordinates, where t=0
// represents p0 and t=1 represents p1. Use v = the vector from p0
// to p1.
double t0 = 0.0;
double t1 = 1.0;
GfVec3d v = p1 - p0;
for (size_t i=0; i < _planes.size(); ++i) {
const GfPlane & plane = _planes[i];
const uint32_t planeBit = 1 << i;
uint32_t p0Bit = p0Mask & planeBit;
uint32_t p1Bit = p1Mask & planeBit;
// Do this only if the points straddle the plane, meaning they
// have different values for the bit.
if (p0Bit == p1Bit)
continue;
// To find the parametric distance t at the intersection of a
// plane and the line defined by (p0 + t * v):
//
// Substitute the intersection point (p0 + t * v) into the
// plane equation to get n . (p0 + t * v) - d = 0
//
// Solve for t: t = - (n . p0 - d) / (n . v)
// But (n . p0 - d) is the distance of p0 from the plane.
double t = -plane.GetDistance(p0) / (plane.GetNormal() * v);
// If p0 is inside and p1 is outside, replace t1. Otherwise,
// replace t0.
if (p0Bit) {
if (t < t1)
t1 = t;
} else {
if (t > t0)
t0 = t;
}
// If there is no line segment left, there's no intersection.
if (t0 > t1)
return false;
}
// If we get here, there's an intersection
return true;
}