-
Notifications
You must be signed in to change notification settings - Fork 232
Expand file tree
/
Copy pathview.cpp
More file actions
1467 lines (1208 loc) · 45.1 KB
/
view.cpp
File metadata and controls
1467 lines (1208 loc) · 45.1 KB
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 2017-2023, Nicholas Sharp and the Polyscope contributors. https://polyscope.run
#include "polyscope/view.h"
#include "polyscope/polyscope.h"
#include "polyscope/utilities.h"
#include "imgui.h"
#include "nlohmann/json.hpp"
using json = nlohmann::json;
namespace polyscope {
namespace view {
// Storage for state variables
int& bufferWidth = state::globalContext.bufferWidth;
int& bufferHeight = state::globalContext.bufferHeight;
int& windowWidth = state::globalContext.windowWidth;
int& windowHeight = state::globalContext.windowHeight;
int& initWindowPosX = state::globalContext.initWindowPosX;
int& initWindowPosY = state::globalContext.initWindowPosY;
bool& windowResizable = state::globalContext.windowResizable;
NavigateStyle& style = state::globalContext.navigateStyle;
UpDir& upDir = state::globalContext.upDir;
FrontDir& frontDir = state::globalContext.frontDir;
float& moveScale = state::globalContext.moveScale;
ViewRelativeMode& viewRelativeMode = state::globalContext.viewRelativeMode;
float& nearClip = state::globalContext.nearClip;
float& farClip = state::globalContext.farClip;
std::array<float, 4>& bgColor = state::globalContext.bgColor;
glm::mat4x4& viewMat = state::globalContext.viewMat;
float& fov = state::globalContext.fov;
ProjectionMode& projectionMode = state::globalContext.projectionMode;
glm::vec3& viewCenter = state::globalContext.viewCenter;
bool& midflight = state::globalContext.midflight;
float& flightStartTime = state::globalContext.flightStartTime;
float& flightEndTime = state::globalContext.flightEndTime;
glm::dualquat& flightTargetViewR = state::globalContext.flightTargetViewR;
glm::dualquat& flightInitialViewR = state::globalContext.flightInitialViewR;
glm::vec3& flightTargetViewT = state::globalContext.flightTargetViewT;
glm::vec3& flightInitialViewT = state::globalContext.flightInitialViewT;
float& flightTargetFov = state::globalContext.flightTargetFov;
float& flightInitialFov = state::globalContext.flightInitialFov;
// Default values
const int defaultWindowWidth = 1280;
const int defaultWindowHeight = 720;
const float defaultNearClipRatio = 0.005f;
const float defaultFarClipRatio = 20.f;
const float defaultFov = 45.;
const float minFov = 5.; // for UI
const float maxFov = 160.; // for UI
// Internal details
bool overrideClipPlanes =
false; // used only for temporary state changes in render passes, so we do not track in context
float overrideNearClipRelative = defaultNearClipRatio;
float overrideFarClipRelative = defaultFarClipRatio;
// Small helpers
namespace { // anonymous helpers
// A default pairing of <up,front> directions to fall back on when something goes wrong.
const std::vector<std::pair<UpDir, FrontDir>> defaultUpFrontPairs{
{UpDir::NegXUp, FrontDir::NegYFront}, {UpDir::XUp, FrontDir::YFront}, {UpDir::NegYUp, FrontDir::NegZFront},
{UpDir::YUp, FrontDir::ZFront}, {UpDir::NegZUp, FrontDir::NegXFront}, {UpDir::ZUp, FrontDir::XFront}};
FrontDir defaultOrthogonalFrontDir(UpDir upDir) {
for (const std::pair<UpDir, FrontDir>& p : defaultUpFrontPairs) {
if (p.first == upDir) return p.second;
}
return FrontDir::ZFront; // fallthrough, should be unused
}
UpDir defaultOrthogonalUpDir(FrontDir frontDir) {
for (const std::pair<UpDir, FrontDir>& p : defaultUpFrontPairs) {
if (p.second == frontDir) return p.first;
}
return UpDir::YUp; // fallthrough, should be unused
}
}; // namespace
std::tuple<int, int> screenCoordsToBufferInds(glm::vec2 screenCoords) {
int xPos = (screenCoords.x * view::bufferWidth) / view::windowWidth;
int yPos = (screenCoords.y * view::bufferHeight) / view::windowHeight;
// clamp to lie in [0,width),[0,height)
xPos = std::max(std::min(xPos, view::bufferWidth - 1), 0);
yPos = std::max(std::min(yPos, view::bufferHeight - 1), 0);
return std::tuple<int, int>(xPos, yPos);
}
glm::ivec2 screenCoordsToBufferIndsVec(glm::vec2 screenCoords) {
glm::ivec2 out;
std::tie(out.x, out.y) = screenCoordsToBufferInds(screenCoords);
return out;
}
glm::vec2 bufferIndsToScreenCoords(int xPos, int yPos) {
return glm::vec2{xPos * static_cast<float>(view::windowWidth) / view::bufferWidth,
yPos * static_cast<float>(view::windowHeight) / view::bufferHeight};
}
glm::vec2 bufferIndsToScreenCoords(glm::ivec2 bufferInds) {
return bufferIndsToScreenCoords(bufferInds.x, bufferInds.y);
}
std::string getCurrentProjectionModeRaycastRule() {
// This is related to the render engine, it returns the name of the
// shader rule which constructs rays for raycasting-based rendering.
// See rules.h
switch (view::projectionMode) {
case ProjectionMode::Perspective:
return "BUILD_RAY_FOR_FRAGMENT_PERSPECTIVE";
case ProjectionMode::Orthographic:
return "BUILD_RAY_FOR_FRAGMENT_ORTHOGRAPHIC";
}
return "";
}
void processRotate(glm::vec2 startP, glm::vec2 endP) {
if (startP == endP) {
return;
}
// Get frame
glm::vec3 frameLookDir, frameUpDir, frameRightDir;
getCameraFrame(frameLookDir, frameUpDir, frameRightDir);
switch (getNavigateStyle()) {
case NavigateStyle::Turntable: {
glm::vec2 dragDelta = endP - startP;
float delTheta = 2.0 * dragDelta.x * moveScale;
float delPhi = 2.0 * dragDelta.y * moveScale;
// Disallow rotations that would almost align the vertical axis
glm::vec3 verticalAxis = getUpVec();
float lim = 0.01f; // controls how close to vertical the view can get
if (glm::dot(frameLookDir, verticalAxis) > 1.0 - lim) {
delPhi = std::min(delPhi, 0.0f);
}
if (glm::dot(frameLookDir, verticalAxis) < -1.0 + lim) {
delPhi = std::max(delPhi, 0.0f);
}
// Translate to center
viewMat = glm::translate(viewMat, view::viewCenter);
// Rotation about the horizontal axis
glm::mat4x4 phiCamR = glm::rotate(glm::mat4x4(1.0), -delPhi, frameRightDir);
viewMat = viewMat * phiCamR;
// Rotation about the vertical axis
glm::vec3 turntableUp;
glm::mat4x4 thetaCamR = glm::rotate(glm::mat4x4(1.0), delTheta, getUpVec());
viewMat = viewMat * thetaCamR;
// Undo centering
viewMat = glm::translate(viewMat, -view::viewCenter);
// Enforce that the view indeed looks towards the center, as it always should with Turntable mode.
// Mostly this will have no effect, but it can prevent gradual numerical drift where the center shifts relvative to
// the view matrix.
lookAt(view::getCameraWorldPosition(), view::viewCenter, view::getUpVec(), false);
break;
}
case NavigateStyle::Free: {
glm::vec2 dragDelta = endP - startP;
float delTheta = 2.0 * dragDelta.x * moveScale;
float delPhi = 2.0 * dragDelta.y * moveScale;
// Translate to center
viewMat = glm::translate(viewMat, view::viewCenter);
// Rotation about the vertical axis
glm::mat4x4 thetaCamR = glm::rotate(glm::mat4x4(1.0), delTheta, frameUpDir);
viewMat = viewMat * thetaCamR;
// Rotation about the horizontal axis
glm::mat4x4 phiCamR = glm::rotate(glm::mat4x4(1.0), -delPhi, frameRightDir);
viewMat = viewMat * phiCamR;
// Undo centering
viewMat = glm::translate(viewMat, -view::viewCenter);
break;
}
case NavigateStyle::Planar: {
// Do nothing
break;
}
case NavigateStyle::Arcball: {
// Map inputs to unit sphere
auto toSphere = [](glm::vec2 v) {
float x = glm::clamp(v.x, -1.0f, 1.0f);
float y = glm::clamp(v.y, -1.0f, 1.0f);
float mag = x * x + y * y;
if (mag <= 1.0) {
return glm::vec3{x, y, -std::sqrt(1.0 - mag)};
} else {
return glm::normalize(glm::vec3{x, y, 0.0});
}
};
glm::vec3 sphereStart = toSphere(startP);
glm::vec3 sphereEnd = toSphere(endP);
glm::vec3 rotAxis = -cross(sphereStart, sphereEnd);
float rotMag = std::acos(glm::clamp(dot(sphereStart, sphereEnd), -1.0f, 1.0f) * moveScale);
glm::mat4 cameraRotate = glm::rotate(glm::mat4x4(1.0), (float)rotMag, glm::vec3(rotAxis.x, rotAxis.y, rotAxis.z));
// Get current camera rotation
glm::mat4x4 R;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
R[i][j] = viewMat[i][j];
}
}
R[3][3] = 1.0;
glm::mat4 update = glm::inverse(R) * cameraRotate * R;
viewMat = viewMat * update;
break;
}
case NavigateStyle::None: {
// Do nothing
break;
}
case NavigateStyle::FirstPerson: {
glm::vec2 dragDelta = endP - startP;
float delTheta = 2.0 * dragDelta.x;
float delPhi = 2.0 * dragDelta.y;
// Rotation about the vertical axis
glm::vec3 rotAx = glm::mat3(viewMat) * getUpVec();
glm::mat4x4 thetaCamR = glm::rotate(glm::mat4x4(1.0), delTheta, rotAx);
viewMat = thetaCamR * viewMat;
// Rotation about the horizontal axis
glm::mat4x4 phiCamR = glm::rotate(glm::mat4x4(1.0), -delPhi, glm::vec3(1.f, 0.f, 0.f));
viewMat = phiCamR * viewMat;
break;
}
}
requestRedraw();
immediatelyEndFlight();
}
void processTranslate(glm::vec2 delta) {
if (getNavigateStyle() == NavigateStyle::None) {
return;
}
if (glm::length(delta) == 0) {
return;
}
// Process a translation
float s = computeRelativeMotionScale();
float movementScale = 0.6f * s * moveScale;
glm::mat4x4 camSpaceT = glm::translate(glm::mat4x4(1.0), movementScale * glm::vec3(delta.x, delta.y, 0.0));
viewMat = camSpaceT * viewMat;
if (getNavigateStyle() == NavigateStyle::Turntable) {
// also translate the turntable center according to the same motion
glm::vec3 oldCenter = view::viewCenter;
glm::vec3 worldspaceT =
glm::transpose(glm::mat3(viewMat)) * glm::vec3(-movementScale * delta.x, -movementScale * delta.y, 0.0);
glm::vec3 newCenter = oldCenter + worldspaceT;
setViewCenterRaw(newCenter);
}
projectCenterToBeValidForView();
requestRedraw();
immediatelyEndFlight();
}
void processClipPlaneShift(float amount) {
if (amount == 0.0) return;
// Adjust the near clipping plane
nearClip += .03 * amount * nearClip;
requestRedraw();
}
void processZoom(float amount) {
if (amount == 0.0) return;
if (getNavigateStyle() == NavigateStyle::None || getNavigateStyle() == NavigateStyle::FirstPerson) {
return;
}
// Translate the camera forwards and backwards
switch (projectionMode) {
case ProjectionMode::Perspective: {
float s = computeRelativeMotionScale();
float totalZoom = 0.15f * s * amount;
// Disallow zooming that would cross the center point
if (getNavigateStyle() == NavigateStyle::Turntable) {
float currSignedDistToCenter = glm::dot(getLookVec(), view::viewCenter - view::getCameraWorldPosition());
float minDistToCenter = computeRelativeMotionScale() * 1e-5;
float maxAllowedZoom = currSignedDistToCenter - minDistToCenter;
totalZoom = glm::min(totalZoom, maxAllowedZoom);
}
glm::mat4x4 camSpaceT = glm::translate(glm::mat4x4(1.0), glm::vec3(0., 0., totalZoom));
viewMat = camSpaceT * viewMat;
break;
}
case ProjectionMode::Orthographic: {
float fovScale = std::min(fov - minFov, maxFov - fov) / (maxFov - minFov);
fov += -fovScale * amount;
fov = glm::clamp(fov, minFov, maxFov);
break;
}
}
immediatelyEndFlight();
requestRedraw();
}
void processKeyboardNavigation(ImGuiIO& io) {
// == Non movement-related
// ctrl-c
if (io.KeyCtrl && render::engine->isKeyPressed('c')) {
std::string outData = view::getCameraJson();
render::engine->setClipboardText(outData);
}
// ctrl-v
if (io.KeyCtrl && render::engine->isKeyPressed('v')) {
std::string clipboardData = render::engine->getClipboardText();
view::setCameraFromJson(clipboardData, true);
}
// == Movement-related
bool hasMovement = false;
if (getNavigateStyle() == NavigateStyle::FirstPerson) {
// WASD-style keyboard navigation
glm::vec3 delta{0.f, 0.f, 0.f};
if (ImGui::IsKeyDown(ImGuiKey_A)) delta.x += 1.f;
if (ImGui::IsKeyDown(ImGuiKey_D)) delta.x += -1.f;
if (ImGui::IsKeyDown(ImGuiKey_Q)) delta.y += 1.f;
if (ImGui::IsKeyDown(ImGuiKey_E)) delta.y += -1.f;
if (ImGui::IsKeyDown(ImGuiKey_W)) delta.z += 1.f;
if (ImGui::IsKeyDown(ImGuiKey_S)) delta.z += -1.f;
if (glm::length(delta) > 0.) {
hasMovement = true;
}
float s = computeRelativeMotionScale();
float movementMult = s * ImGui::GetIO().DeltaTime * moveScale;
glm::mat4x4 camSpaceT = glm::translate(glm::mat4x4(1.0), movementMult * delta);
viewMat = camSpaceT * viewMat;
}
if (hasMovement) {
immediatelyEndFlight();
requestRedraw();
}
}
void processSetCenter(glm::vec2 screenCoords) {
PickResult pickResult = pickAtScreenCoords(screenCoords);
if (pickResult.isHit) {
setViewCenterAndLookAt(pickResult.position, true);
}
}
void invalidateView() { viewMat = glm::mat4x4(std::numeric_limits<float>::quiet_NaN()); }
bool viewIsValid() {
bool allFinite = true;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
if (!std::isfinite(viewMat[i][j])) {
allFinite = false;
}
}
}
return allFinite;
}
void ensureViewValid() {
if (!viewIsValid()) {
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
if (!std::isfinite(viewMat[i][j])) {
viewMat[i][j] = 0.;
}
}
}
resetCameraToHomeView();
}
}
float computeRelativeMotionScale() {
switch (viewRelativeMode) {
case ViewRelativeMode::CenterRelative: {
float distToCenter = glm::length(view::viewCenter - view::getCameraWorldPosition());
return distToCenter;
}
case ViewRelativeMode::LengthRelative: {
return state::lengthScale;
}
}
return -1.; // should be unreachable
}
void projectCenterToBeValidForView() {
// If necessary, move the view center to be one that is compatible with the current view matrix and navigation style.
switch (style) {
case NavigateStyle::Turntable: {
// Center must lie exactly along the camera look direction
glm::vec3 camPos = getCameraWorldPosition();
glm::vec3 camLookDir, camUpDir, camRightDir;
getCameraFrame(camLookDir, camUpDir, camRightDir);
glm::vec3 sceneUpDir = getUpVec();
glm::vec3 vecToCenter = viewCenter - camPos;
float distToCenter = glm::length(vecToCenter);
glm::vec3 newCenter = camPos + camLookDir * distToCenter;
setViewCenterRaw(newCenter);
break;
}
case NavigateStyle::Planar:
case NavigateStyle::Free:
case NavigateStyle::Arcball:
case NavigateStyle::None:
case NavigateStyle::FirstPerson:
// No constraints
break;
}
}
glm::mat4 computeHomeView() {
glm::vec3 target = view::viewCenter;
glm::vec3 upDir = getUpVec();
glm::vec3 frontDir = getFrontVec();
if (std::fabs(glm::dot(upDir, frontDir)) > 0.01) {
// if the user has foolishly set upDir and frontDir to be along the same axis,
// change front dir so lookAt can do something sane
frontDir = circularPermuteEntries(frontDir);
}
float L = state::lengthScale;
glm::vec3 cameraLoc = state::center() + 0.1f * L * upDir + 1.5f * L * frontDir;
return glm::lookAt(cameraLoc, target, upDir);
}
void resetCameraToHomeView() {
// WARNING: Duplicated here and in flyToHomeView()
// If the view is invalid, don't change it. It will get reset before the first call to show().
if (!viewIsValid()) {
return;
}
view::viewCenter = state::center();
viewMat = computeHomeView();
fov = defaultFov;
nearClip = defaultNearClipRatio;
farClip = defaultFarClipRatio;
requestRedraw();
}
void flyToHomeView() {
// WARNING: Duplicated here and in resetCameraToHomeView()
view::viewCenter = state::center();
glm::mat4x4 T = computeHomeView();
float Tfov = defaultFov;
nearClip = defaultNearClipRatio;
farClip = defaultFarClipRatio;
startFlightTo(T, Tfov);
}
void updateViewAndChangeNavigationStyle(NavigateStyle newStyle, bool flyTo) {
NavigateStyle oldStyle = view::style;
view::style = newStyle;
if (viewIsValid()) {
// for a few combinations of views, we can leave the camera where it is rather than resetting to the home view
if (newStyle == NavigateStyle::Free) {
// nothing needed
} else if (newStyle == NavigateStyle::FirstPerson && oldStyle == NavigateStyle::Turntable) {
// nothing needed
} else if (newStyle == NavigateStyle::Turntable) {
// leave the camera in the same location
lookAt(getCameraWorldPosition(), view::viewCenter, flyTo);
} else {
// General case, depending only on the target style
glm::mat4x4 T = computeHomeView();
if (flyTo) {
startFlightTo(T, view::fov);
} else {
viewMat = T;
}
}
requestRedraw();
}
}
void updateViewAndChangeUpDir(UpDir newUpDir, bool flyTo) {
view::upDir = newUpDir;
if (std::fabs(dot(view::getUpVec(), view::getFrontVec())) > 0.1) {
// if the user has foolishly set upDir and frontDir to be along the same axis, fix it
view::frontDir = defaultOrthogonalFrontDir(view::upDir);
}
if (viewIsValid()) {
switch (style) {
case NavigateStyle::Turntable:
case NavigateStyle::Planar:
case NavigateStyle::Arcball:
case NavigateStyle::FirstPerson: {
glm::vec3 lookDir = getCameraParametersForCurrentView().getLookDir();
if (std::fabs(dot(view::getUpVec(), lookDir)) < 0.01) {
// if the new up direction is colinear with the direction we're currently looking
lookDir = getFrontVec();
}
glm::vec3 camPos = getCameraWorldPosition();
lookAt(camPos, camPos + lookDir * state::lengthScale, flyTo);
break;
}
case NavigateStyle::Free:
case NavigateStyle::None:
// No change needed
break;
}
requestRedraw();
}
}
void updateViewAndChangeFrontDir(FrontDir newFrontDir, bool flyTo) {
view::frontDir = newFrontDir;
if (std::fabs(dot(view::getUpVec(), view::getFrontVec())) > 0.1) {
// if the user has foolishly set upDir and frontDir to be along the same axis, fix it
setUpDir(defaultOrthogonalUpDir(view::frontDir), flyTo);
}
if (viewIsValid()) {
switch (style) {
case NavigateStyle::Turntable:
case NavigateStyle::Planar:
case NavigateStyle::Arcball:
case NavigateStyle::Free:
case NavigateStyle::FirstPerson:
case NavigateStyle::None:
// Currently no views require updating to conform to the front dir, it is just for the default pose
break;
}
requestRedraw();
}
}
void setViewCenterAndLookAt(glm::vec3 newCenter, bool flyTo) {
view::viewCenter = newCenter;
if (viewIsValid()) {
// Update the view to be relative to the new center
// This is necessary for some view modes like Turntable, where the viewMat is in a constrained family with respect
// to the center.
switch (style) {
case NavigateStyle::Turntable:
case NavigateStyle::Arcball:
case NavigateStyle::Free:
case NavigateStyle::FirstPerson:
// this is a decent baseliny policy that always does _something_ sane
// might want nicer policies for certain cameras
lookAt(getCameraWorldPosition(), view::viewCenter, flyTo);
break;
case NavigateStyle::Planar: {
// move the camera within the planar constraint
glm::vec3 lookDir = getCameraParametersForCurrentView().getLookDir();
glm::vec3 camPos = getCameraWorldPosition();
glm::vec3 targetVec = newCenter - camPos;
glm::vec3 planarDir = getFrontVec();
glm::vec3 newCamPos = newCenter - planarDir * glm::dot(planarDir, targetVec);
lookAt(newCamPos, view::viewCenter, flyTo);
break;
}
case NavigateStyle::None:
// no change needed
break;
}
requestRedraw();
}
}
void setViewCenterAndProject(glm::vec3 newCenter) {
view::viewCenter = newCenter;
projectCenterToBeValidForView();
}
void setViewCenterRaw(glm::vec3 newCenter) { view::viewCenter = newCenter; }
glm::vec3 getViewCenter() { return view::viewCenter; }
void lookAt(glm::vec3 cameraLocation, glm::vec3 target, bool flyTo) {
lookAt(cameraLocation, target, getUpVec(), flyTo);
}
void lookAt(glm::vec3 cameraLocation, glm::vec3 target, glm::vec3 upDir, bool flyTo) {
immediatelyEndFlight();
glm::mat4x4 targetView = glm::lookAt(cameraLocation, target, upDir);
// Give a sane warning for invalid inputs
bool isFinite = true;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
if (!std::isfinite(targetView[i][j])) {
isFinite = false;
}
}
}
if (!isFinite) {
warning("lookAt() yielded an invalid view. Is the location same as the target? Is the look direction collinear "
"with the up direction?");
// just continue after; our view handling will take care of the NaN and set it to the default view
}
if (flyTo) {
startFlightTo(targetView, fov);
} else {
viewMat = targetView;
projectCenterToBeValidForView();
requestRedraw();
}
}
void setWindowSize(int width, int height) {
view::windowWidth = width;
view::windowHeight = height;
if (isInitialized()) {
render::engine->applyWindowSize();
}
}
std::tuple<int, int> getWindowSize() { return std::tuple<int, int>(view::windowWidth, view::windowHeight); }
std::tuple<int, int> getBufferSize() { return std::tuple<int, int>(view::bufferWidth, view::bufferHeight); }
void setViewToCamera(const CameraParameters& p) {
viewMat = p.getE();
fov = p.getFoVVerticalDegrees();
// aspectRatio = p.focalLengths.x / p.focalLengths.y; // TODO should be
// flipped?
projectCenterToBeValidForView();
}
CameraParameters getCameraParametersForCurrentView() {
ensureViewValid();
float aspectRatio = (float)bufferWidth / bufferHeight;
return CameraParameters(CameraIntrinsics::fromFoVDegVerticalAndAspect(fov, aspectRatio),
CameraExtrinsics::fromMatrix(viewMat));
}
void setCameraViewMatrix(glm::mat4 mat) {
viewMat = mat;
projectCenterToBeValidForView();
requestRedraw();
}
glm::mat4 getCameraViewMatrix() { return viewMat; }
void setVerticalFieldOfViewDegrees(float newVal) {
view::fov = newVal;
requestRedraw();
}
ProjectionMode getProjectionMode() { return projectionMode; }
void setProjectionMode(ProjectionMode newMode) {
projectionMode = newMode;
internal::lazy::projectionMode = newMode; // update the lazy property right now, so we don't pay for a refresh twice
refresh();
requestRedraw();
}
ViewRelativeMode getViewRelativeMode() { return viewRelativeMode; }
void setViewRelativeMode(ViewRelativeMode newMode) {
viewRelativeMode = newMode;
requestRedraw();
}
void setClipPlanes(float newNearClip, float newFarClip) {
nearClip = newNearClip;
farClip = newFarClip;
requestRedraw();
}
std::tuple<float, float> getClipPlanes() { return std::tuple<float, float>(nearClip, farClip); }
float getVerticalFieldOfViewDegrees() { return view::fov; }
float getAspectRatioWidthOverHeight() { return (float)bufferWidth / bufferHeight; }
glm::mat4 getCameraPerspectiveMatrix() {
// Set the clip plane
float absNearClip, absFarClip;
if (overrideClipPlanes) {
absNearClip = overrideNearClipRelative * state::lengthScale;
absFarClip = overrideFarClipRelative * state::lengthScale;
} else {
std::tie(absNearClip, absFarClip) = computeClipPlanes();
}
float fovRad = glm::radians(fov);
float aspectRatio = (float)bufferWidth / bufferHeight;
switch (projectionMode) {
case ProjectionMode::Perspective: {
return glm::perspective(fovRad, aspectRatio, absNearClip, absFarClip);
break;
}
case ProjectionMode::Orthographic: {
float vert = tan(fovRad / 2.) * state::lengthScale * 2.;
float horiz = vert * aspectRatio;
return glm::ortho(-horiz, horiz, -vert, vert, absNearClip, absFarClip);
break;
}
}
return glm::mat4(1.0f); // unreachable
}
glm::vec3 getCameraWorldPosition() {
// This will work no matter how the view matrix is constructed...
glm::mat4 invViewMat = inverse(getCameraViewMatrix());
return glm::vec3{invViewMat[3][0], invViewMat[3][1], invViewMat[3][2]};
}
void getCameraFrame(glm::vec3& lookDir, glm::vec3& upDir, glm::vec3& rightDir) {
glm::mat3x3 R;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
R[i][j] = viewMat[i][j];
}
}
glm::mat3x3 Rt = glm::transpose(R);
lookDir = Rt * glm::vec3(0.0, 0.0, -1.0);
upDir = Rt * glm::vec3(0.0, 1.0, 0.0);
rightDir = Rt * glm::vec3(1.0, 0.0, 0.0);
}
glm::vec3 getLookVec() {
glm::mat3x3 R;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
R[i][j] = viewMat[i][j];
}
}
glm::mat3x3 Rt = glm::transpose(R);
return Rt * glm::vec3(0.0, 0.0, -1.0);
}
glm::vec3 screenCoordsToWorldRay(glm::vec2 screenCoords) {
glm::mat4 view = getCameraViewMatrix();
glm::mat4 proj = getCameraPerspectiveMatrix();
glm::vec4 viewport = {0., 0., view::windowWidth, view::windowHeight};
glm::vec3 screenPos3{screenCoords.x, view::windowHeight - screenCoords.y, 0.};
glm::vec3 worldPos = glm::unProject(screenPos3, view, proj, viewport);
glm::vec3 worldRayDir = glm::normalize(glm::vec3(worldPos) - getCameraWorldPosition());
return worldRayDir;
}
glm::vec3 bufferIndsToWorldRay(glm::vec2 bufferInds) { return bufferCoordsToWorldRay(bufferInds); }
glm::vec3 bufferCoordsToWorldRay(glm::vec2 bufferCoords) {
glm::mat4 view = getCameraViewMatrix();
glm::mat4 proj = getCameraPerspectiveMatrix();
glm::vec4 viewport = {0., 0., view::bufferWidth, view::bufferHeight};
glm::vec3 screenPos3{bufferCoords.x, view::bufferHeight - bufferCoords.y, 0.};
glm::vec3 worldPos = glm::unProject(screenPos3, view, proj, viewport);
glm::vec3 worldRayDir = glm::normalize(glm::vec3(worldPos) - getCameraWorldPosition());
return worldRayDir;
}
std::tuple<float, float> computeClipPlanes() {
float s = computeRelativeMotionScale();
float absFarClip = farClip * s;
// it's tempting to compute both near and far clip planes from the scale,
// but computing the near clip plane this way gives flickering very quickly when zooming in on surface details
// float absNearClip = nearClip * s;
// instead, always use the length scale for the near clip plane
float absNearClip = nearClip * state::lengthScale;
return std::make_tuple(absNearClip, absFarClip);
}
glm::vec3 screenCoordsAndDepthToWorldPosition(glm::vec2 screenCoords, float clipDepth) {
if (clipDepth == 1.) {
// if we didn't hit anything in the depth buffer, just return infinity
float inf = std::numeric_limits<float>::infinity();
return glm::vec3{inf, inf, inf};
}
glm::mat4 view = getCameraViewMatrix();
glm::mat4 viewInv = glm::inverse(view);
glm::mat4 proj = getCameraPerspectiveMatrix();
glm::mat4 projInv = glm::inverse(proj);
// glm::vec2 depthRange = {0., 1.}; // no support for nonstandard depth range, currently
// convert depth to world units
glm::vec2 screenPos{screenCoords.x / static_cast<float>(view::windowWidth),
1.f - screenCoords.y / static_cast<float>(view::windowHeight)};
float z = clipDepth * 2.0f - 1.0f;
glm::vec4 clipPos = glm::vec4(screenPos * 2.0f - 1.0f, z, 1.0f);
glm::vec4 viewPos = projInv * clipPos;
viewPos /= viewPos.w;
glm::vec4 worldPos = viewInv * viewPos;
worldPos /= worldPos.w;
return glm::vec3(worldPos);
}
void startFlightTo(const CameraParameters& p, float flightLengthInSeconds) {
startFlightTo(p.getE(), p.getFoVVerticalDegrees(), flightLengthInSeconds);
}
void startFlightTo(const glm::mat4& T, float targetFov, float flightLengthInSeconds) {
flightStartTime = ImGui::GetTime();
flightEndTime = ImGui::GetTime() + flightLengthInSeconds;
// NOTE: we interpolate the _inverse_ view matrix (then invert back), because it looks better
// when far from the origin
// Initial parameters
glm::mat3x4 Rstart;
glm::vec3 Tstart;
glm::mat4 viewInv = glm::inverse(getCameraViewMatrix());
splitTransform(viewInv, Rstart, Tstart);
flightInitialViewR = glm::dualquat_cast(Rstart);
flightInitialViewT = Tstart;
flightInitialFov = fov;
// Final parameters
glm::mat3x4 Rend;
glm::vec3 Tend;
glm::mat4 Tinv = glm::inverse(T);
splitTransform(Tinv, Rend, Tend);
flightTargetViewR = glm::dualquat_cast(Rend);
flightTargetViewT = Tend;
flightTargetFov = targetFov;
midflight = true;
}
void immediatelyEndFlight() { midflight = false; }
void updateFlight() {
// NOTE: we interpolate the _inverse_ view matrix (then invert back), because it looks better
// when far from the origin
if (midflight) {
if (ImGui::GetTime() > flightEndTime) {
// Flight is over, ensure we end exactly at target location
midflight = false;
viewMat = glm::inverse(buildTransform(glm::mat3x4_cast(flightTargetViewR), flightTargetViewT));
fov = flightTargetFov;
} else {
// normalized time for spline on [0,1]
float t = (ImGui::GetTime() - flightStartTime) / (flightEndTime - flightStartTime);
float tSmooth = glm::smoothstep(0.f, 1.f, t);
// linear spline
glm::dualquat interpR = glm::lerp(flightInitialViewR, flightTargetViewR, tSmooth);
glm::vec3 interpT = glm::mix(flightInitialViewT, flightTargetViewT, tSmooth);
viewMat = glm::inverse(buildTransform(glm::mat3x4_cast(interpR), interpT));
// linear spline
fov = (1.0f - t) * flightInitialFov + t * flightTargetFov;
}
requestRedraw(); // flight is still happening, draw again next frame
}
}
std::string getViewAsJson() {
// Get the view matrix (note weird glm indexing, glm is [col][row])
glm::mat4 viewMat = getCameraViewMatrix();
std::array<float, 16> viewMatFlat;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
viewMatFlat[4 * i + j] = viewMat[j][i];
}
}
// Build the json object
json j = {
{"fov", fov},
{"viewMat", viewMatFlat},
{"nearClip", nearClip},
{"farClip", farClip},
{"windowWidth", view::windowWidth},
{"windowHeight", view::windowHeight},
{"projectionMode", enum_to_string(view::projectionMode)},
{"navigateStyle", enum_to_string(view::style)},
{"upDir", enum_to_string(view::upDir)},
{"frontDir", enum_to_string(view::frontDir)},
{"viewRelativeMode", enum_to_string(view::viewRelativeMode)},
{"viewCenter", {view::viewCenter.x, view::viewCenter.y, view::viewCenter.z}},
};
std::string outString = j.dump();
return outString;
}
std::string getCameraJson() { return getViewAsJson(); }
void setViewFromJson(std::string jsonData, bool flyTo) {
// Values will go here
glm::mat4 newViewMat = viewMat;
float newFov = fov;
float newNearClipRatio = nearClip;
float newFarClipRatio = farClip;
int windowWidth = view::windowWidth;
int windowHeight = view::windowHeight;
try {
// Deserialize
json j;
std::stringstream s(jsonData);
s >> j;
// Read out the data
// Get the clip ratios, but only if present
bool clipChanged = false;
if (j.find("nearClip") != j.end()) {
newNearClipRatio = j["nearClip"];
clipChanged = true;
}
if (j.find("farClip") != j.end()) {
newFarClipRatio = j["farClip"];
clipChanged = true;