-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDisplay.cpp
More file actions
2975 lines (2584 loc) · 127 KB
/
Copy pathDisplay.cpp
File metadata and controls
2975 lines (2584 loc) · 127 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 (C) 2024: Arizona Board of Regents on Behalf of the University of Arizona
*/
#ifdef WIN32
#define _USE_MATH_DEFINES
#else
#include <arpa/inet.h> // For ntohl()
#endif
#include <cmath>
#include <iostream>
#include <thread>
#include <atomic>
#include <mutex>
#include <chrono>
#include <map>
#define GLM_ENABLE_EXPERIMENTAL
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/quaternion.hpp>
#include <glm/gtx/euler_angles.hpp>
#include <glm/gtx/matrix_decompose.hpp>
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include "Display.h"
using namespace asdp::render;
namespace asdp {
namespace render {
/// @brief Static class member to ensure that GLFW is initialized and terminated when this library is
/// loaded and unloaded.
class GLFWInitializer {
public:
GLFWInitializer() {
if (!glfwInit()) {
std::cerr << "asdp::Render::Display submodule: Failed to initialize GLFW" << std::endl;
}
}
~GLFWInitializer() {
glfwTerminate();
}
};
static GLFWInitializer initGLFW;
} // namespace render
} // namespace asdp}
/// Ensure that we only create one window at a time.
std::mutex Display::m_windowMutex;
//==============================================================================
// Structures and methods for Display class.
/// @brief Implementation details for the Display class to hide #includes from users of the Display class.
class asdp::render::Display::DisplayImpl {
public:
/// Window that will be used to display the view.
GLFWwindow* m_window = nullptr;
//===========================
// Machinery required for borrowing and returning the context from DisplayThread.
// We need to be sure that the context is available before borrowing it, so we have
// and atomic to track that. We need to ensure that we don't try to use the context
// while it is being borrowed, so we have a mutex to protect that.
// Some operating systems (Windows, for example), require the OpenGL context to be
// shared to be active on the thread that is creating the new window.
// NOTE: All derived classes must set m_contextAvailable to true after the context is created
// and ready to be borrowed.
std::atomic_bool m_contextAvailable{ false };
// NOTE: All derived classes must lock m_contextMutex when they are using the context and must
// periodically unlock it so that it can be borrowed to create another context that shares objects
// with this one. On Linux, this must be an extended period of time (not just a few instructions)
// so that another thread can get a chance to lock the mutex.
std::mutex m_contextMutex;
};
Display::Display(std::shared_ptr<Composite> composite,
std::shared_ptr<CoreClient> client, uint8_t triggerID, uint32_t triggerAheadMicroseconds,
uint32_t depthAheadMicroseconds, std::array<float, 3> viewpointOffset,
std::shared_ptr<EventHandlers> handlers, void* userData)
: m_viewpointOffset(viewpointOffset)
, m_composite(composite)
, m_eventHandlers(handlers)
, m_userData(userData)
, m_nowPlaying(true)
, m_showCameraNames(false)
, m_client(client)
, m_triggerID(triggerID)
, m_offsetMicroseconds(triggerAheadMicroseconds)
, m_depthAheadMicroseconds(depthAheadMicroseconds)
, m_done(false)
, m_impl(new DisplayImpl)
{
if (m_client) {
Status status = m_client->GetTimer(m_timer);
if (status != OKAY) {
m_timer.reset();
}
}
}
Display::~Display()
{
// Call the Quit() virtual function to stop all threads and clean up resources.
Quit();
m_impl.reset();
}
bool Display::Quit()
{
// Stop the display thread, if it is running.
m_done = true;
if (m_displayThread.joinable()) {
m_displayThread.join();
}
m_status = "Done";
// Clean up all resources, including those kept in shared pointers.
m_timer.reset();
m_composite.reset();
m_client.reset();
return true;
}
void Display::SetNowPlaying(bool nowPlaying)
{
m_nowPlaying = nowPlaying;
}
std::string Display::GetStatus() const
{
return m_status;
}
bool Display::TriggerCameras(std::chrono::steady_clock::time_point when)
{
if ((m_client == nullptr) || (m_timer == nullptr) || (m_triggerID == 0)) {
// No client or timer, so we can't trigger the cameras.
return true;
}
// Determine the time to trigger the cameras by subtracting the microseconds
// offset from the time to trigger the cameras and then converting to Core time.
std::chrono::steady_clock::time_point sysTime = when - std::chrono::microseconds(m_offsetMicroseconds);
Time coreTime;
Status status = m_timer->GetCoreTime(coreTime, sysTime);
if (status != OKAY) {
return false;
}
// Send a software-trigger command to the client.
CommandPacketSoftwareTrigger packet(m_triggerID, coreTime);
if (packet.GetConstructorStatus() != OKAY) {
return false;
}
status = m_client->SendCommandPacket(packet);
if (status != OKAY) {
return false;
}
// It worked
return true;
}
bool Display::BorrowContext()
{
if (m_impl == nullptr) {
return false;
}
// Wait until the context is available.
while (!m_impl->m_contextAvailable) {
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
// Grab the context mutex.
m_impl->m_contextMutex.lock();
// Make the context current on the calling thread.
glfwMakeContextCurrent(m_impl->m_window);
return true;
}
bool Display::ReturnContext()
{
if (m_impl == nullptr) {
return false;
}
// Release the current context.
glfwMakeContextCurrent(nullptr);
// Release the context mutex.
m_impl->m_contextMutex.unlock();
return true;
}
//==============================================================================
// Structures and methods for DisplayWindow class.
/// @brief Implementation details for the DisplayWindow class to hide #includes from users of the DisplayWindow class.
class asdp::render::DisplayWindow::DisplayWindowImpl {
public:
/// Horizontal field of view in degrees.
float m_horizontalFOVDegrees {90.0f};
/// Views to be rendered.
std::vector<asdp::render::ViewRenderInfo> m_views;
/// Angles of rotation in degrees based on keyboard and/or joystick input.
/// rotation is around the original Z axis, then the original Z axis.
float m_rotationZDegrees {0.0f};
float m_rotationXDegrees = {0.0f};
/// Last time we checked the keyboard, used to control motion rate.
std::chrono::steady_clock::time_point m_lastKeyboardCheck;
/// Is the left mouse button pressed?
bool m_leftMouseButtonPressed = false;
/// The cursor position when the left mouse button was pressed.
double m_mousePressedX = 0.0;
double m_mousePressedY = 0.0;
/// Last time we adjusted due to the mouse, used to control motion rate.
std::chrono::steady_clock::time_point m_lastMouseMotion;
/// Time point to start rendering the next frame.
std::chrono::steady_clock::time_point m_nextRenderTime;
/// Time point to start computing the depth for the next frame;
std::chrono::steady_clock::time_point m_nextDepthTime;
/// Time point in the middle of the next frame we will render.
std::chrono::steady_clock::time_point m_nextFrameTime;
/// Whether the space bar was pressed during the last loop, used to toggle play/pause.
bool m_spacePressed = false;
/// Whether or no the 'd' key was pressed during the last loop, used to toggle depth computation.
bool m_dPressed = false;
bool m_displayingDepth = false;
/// Whether or not the '[' key was pressed during the last loop, used to ajust active camera index.
bool m_leftBracketPressed = false;
/// Whether or not the ']' key was pressed during the last loop, used to ajust active camera index.
bool m_rightBracketPressed = false;
// Whether or not the 's' key was pressed during the last loop, used to save camera configuration.
bool m_sPressed = false;
/// Whether or not the 'g' key was pressed during the last loop, used to toggle auto-calibration.
bool m_gPressed = false;
/// Whether or not the 'o' key was pressed during the last loop, used to toggle overview plus detail view.
bool m_oPressed = false;
/// Whether or not the 'c' key was pressed during the last loop, used to toggle camera names display.
bool m_cPressed = false;
/// Whether or not the 'a' key was pressed during the last loop, used to toggle annotations display.
bool m_aPressed = false;
/// Index of the joystick to use, or -1 if no joystick is to be used.
int m_glfwJoystickIndex = -1;
/// Name of joysticks that should be flipping in the Y axis.
std::vector<std::string> m_flipYJoysticks = { "Logitech Extreme 3D", "Logitech Logitech Extreme 3D" };
/// Scale of the joystick input in Y axis, flipped if the joystick is on the list above.
float m_joystickScaleY = 1.0f;
//======================================
// Added by Sang Yoon to bind trigger button(s) of a game pad to pausing/resuming action
bool m_triggerPressed = false;
//======================================
};
DisplayWindow::DisplayWindow(std::string windowName, std::shared_ptr<Composite> composite,
std::shared_ptr<CoreClient> client, uint8_t triggerID, uint32_t triggerAheadMicroseconds,
uint32_t depthAheadMicroseconds, std::array<float, 3> viewpointOffset,
float fps, uint32_t renderAheadMicroseconds,
int desiredWidth, int desiredHeight, float horizontalFOVDegrees,
std::string joystick, Display* sharedWindow,
bool fullScreen, int desiredDisplay, bool hidden,
std::shared_ptr<EventHandlers> handlers, void* userData,
RenderTimingInfo* timingInfo, bool replaying)
: Display(composite, client, triggerID, triggerAheadMicroseconds, depthAheadMicroseconds, viewpointOffset, handlers, userData)
, m_timingInfo(timingInfo)
, m_replaying(replaying)
, m_impl(new DisplayWindowImpl)
{
// Check our parameters.
if ((desiredWidth <= 0) || (desiredHeight <= 0) || (horizontalFOVDegrees <= 0.0f)) {
m_status = "Invalid window size or field of view";
return;
}
// Store info from the constructor.
m_impl->m_horizontalFOVDegrees = horizontalFOVDegrees;
// Construct a single view to be used. We base is on the requested window size and we compute a
// field of view that is 40 degrees total horizontal and the correct aspect ratio vertical.
ViewRenderInfo view;
SetViewportSizeAndFOVs(view, desiredWidth, desiredHeight);
view.viewpoint = m_viewpointOffset;
m_impl->m_views.push_back(view);
// Start the rendering thread.
m_displayThread = std::thread(&DisplayWindow::DisplayThread, this, windowName,
fps, renderAheadMicroseconds,
desiredWidth, desiredHeight, horizontalFOVDegrees,
joystick, sharedWindow, fullScreen, desiredDisplay, hidden);
// Wait until either the context is ready or there has been a failure so that the
// constructor does not return before the rendering thread is ready.
while (!Display::m_impl->m_contextAvailable && (m_status == "")) {
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
}
DisplayWindow::~DisplayWindow()
{
// Make sure we're done with our rendering state and then clean up.
Quit();
m_impl.reset();
}
void DisplayWindow::SetViewportSizeAndFOVs(ViewRenderInfo& viewInfo, int width, int height)
{
if (m_impl == nullptr) {
return;
}
if ((width == 0) || (height == 0)) {
glfwGetWindowSize(Display::m_impl->m_window, &width, &height);
viewInfo.width = width;
viewInfo.height = height;
}
viewInfo.leftHalfFOV = -m_impl->m_horizontalFOVDegrees / 2.0f;
viewInfo.rightHalfFOV = m_impl->m_horizontalFOVDegrees / 2.0f;
// The vertical field of view is based on the aspect ratio of the window. But the aspect ratio
// is the in-plane width divided by the in-plane height. The horizontal and vertical fields of view
// are based on the tangents.
double aspectRatio = static_cast<double>(viewInfo.height) / static_cast<double>(viewInfo.width);
double halfWidth = tan(glm::radians(m_impl->m_horizontalFOVDegrees / 2.0));
double halfHeight = halfWidth * aspectRatio;
double halfAngle = glm::degrees(atan(halfHeight));
//======================================
// Added by Sang Yoon to calculate a vertical FOV for cylindrical projection
if (this->m_composite->m_CP_enabled)
halfAngle = m_impl->m_horizontalFOVDegrees / 2.0 * aspectRatio;
//======================================
viewInfo.bottomHalfFOV = -halfAngle;
viewInfo.topHalfFOV = halfAngle;
}
void DisplayWindow::DisplayThread(std::string windowName,
float fps, uint32_t renderAheadMicroseconds,
int desiredWidth, int desiredHeight, float horizontalFOVDegrees,
std::string joystick, Display* sharedWindow,
bool fullScreen, int desiredDisplay, bool hidden)
{
{
{
// Hold the window mutex so that only one window can be created at a time.
std::lock_guard<std::mutex> windowLock(m_windowMutex);
// Set the window visibility.
glfwWindowHint(GLFW_VISIBLE, !hidden);
// Tell it not to iconify full-screen windows that lose focus.
glfwWindowHint(GLFW_AUTO_ICONIFY, GLFW_FALSE);
// Create a windowed mode window and its OpenGL context.
// This must be done in the same thread that will do the rendering so that the window events will
// be handled properly on all architectures.
// We must make the OpenGL context of the window we want to share current on this thread
// if we are sharing it by borrowing it and then returning it once the window is open because
// Windows requires it to be current.
GLFWwindow* windowToShare = nullptr;
if (sharedWindow) {
windowToShare = sharedWindow->m_impl->m_window;
if (!sharedWindow->BorrowContext()) {
m_status = "Failed to borrow context from shared window";
return;
}
}
Display::m_impl->m_window = glfwCreateWindow(desiredWidth, desiredHeight, windowName.c_str(), nullptr,
windowToShare);
if (sharedWindow) {
if (!sharedWindow->ReturnContext()) {
m_status = "Failed to return context to shared window";
return;
}
}
}
// Verify that the window was created.
if (!Display::m_impl->m_window) {
m_status = "Failed to create GLFW window";
return;
}
// Determine the full-screen monitor to use, if any.
GLFWmonitor* fullScreenMonitor = nullptr;
if (fullScreen) {
int count;
GLFWmonitor** monitors = glfwGetMonitors(&count);
if ((count == 0) || !monitors) {
m_status = "No monitors for fullscreen";
return;
}
if (desiredDisplay >= count) {
m_status = "Invalid monitor requested (index larger than available monitors)";
return;
}
fullScreenMonitor = monitors[desiredDisplay];
}
// If we're displaying full-screen engage that here along with specifying the refresh rate.
if (fullScreenMonitor) {
glfwSetWindowMonitor(Display::m_impl->m_window, fullScreenMonitor, 0, 0, desiredWidth, desiredHeight, fps);
}
// Open the joystick if there is one asked for and there is one present.
// We currently only support GLFW-based joysticks, which are specified by the string
// "GLFW::#". The # is the number of the joystick to open, starting with 0. GLFW
// joysticks are alwasy open, so we just need to record which one to use if it is
// present.
if (!joystick.empty() && (joystick.substr(0, 6) == "GLFW::")) {
int joyNum = std::stoi(joystick.substr(6));
if (glfwJoystickPresent(joyNum)) {
m_impl->m_glfwJoystickIndex = joyNum;
// See if we should flip the Y-axis value.
const char* joystickName = glfwGetJoystickName(joyNum);
if (std::find(m_impl->m_flipYJoysticks.begin(), m_impl->m_flipYJoysticks.end(),
glfwGetJoystickName(joyNum)) != m_impl->m_flipYJoysticks.end()) {
m_impl->m_joystickScaleY = -1.0f;
}
}
}
// Grab the context mutex for the duration of the setup. Once we have it, we know
// that the context is not active in another thread.
// DO NOT do any GLFW calls while holding the context -- it causes rare hangs on Linux.
std::lock_guard<std::mutex> lock(Display::m_impl->m_contextMutex);
glfwMakeContextCurrent(Display::m_impl->m_window);
// Initialize GLEW in our context. It is okay to initialize it more than once.
glewExperimental = true;
if (glewInit() != GLEW_OK) {
m_status = "Failed to initialize GLEW";
return;
}
// Clear any GL error that Glew caused. Apparently on Non-Windows
// platforms, this can cause a spurious error 1280.
glGetError();
// Release the window's current context in case another Display wants to borrow it.
glfwMakeContextCurrent(nullptr);
// After we're done with the context for set-up and have released it, indicate that the context is available
// for borrowing.
glFinish();
Display::m_impl->m_contextAvailable = true;
}
// Loop until the display is done.
bool frameCompleted = false;
auto lastJoystickCheck = std::chrono::steady_clock::now();
while (!m_done) {
// Poll for and process events without a context to avoid multiple threads trying to get
// the context at the same time.
glfwPollEvents();
// Determine the scan-out time of the frame (center of the image).
Time renderTime;
m_timer->GetCoreTime(renderTime, std::chrono::steady_clock::now());
if (!m_replaying) {
double frameTime = 1.0 / fps;
double middleOfNextFrameOffset = frameTime / 2.0 + renderAheadMicroseconds / 1e6;
uint32_t seconds = static_cast<uint32_t>(middleOfNextFrameOffset);
uint32_t microseconds = (middleOfNextFrameOffset - seconds) * 1e6;
renderTime += Time(seconds, microseconds);
}
// Adjust render time if we're paused.
if (m_pauseTime) {
renderTime = *m_pauseTime;
}
// Wait until it is time to compute depth for the next frame. We must busy-wait here to avoid having our
// thread swapped out for longer than we want.
while (std::chrono::steady_clock::now() < m_impl->m_nextDepthTime) {
}
if (m_eventHandlers && m_eventHandlers->CopyDepthInfo) {
// Grab the context mutex for the duration of the depth calculations. Once we have it, we know
// that the context is not active in another thread.
// Make the window's context current.
// DO NOT do any GLFW calls while holding the context -- it causes rare hangs on Linux.
std::lock_guard<std::mutex> lock(Display::m_impl->m_contextMutex);
glfwMakeContextCurrent(Display::m_impl->m_window);
#if !defined(NDEBUG)
GLenum err = glGetError();
if (err != GL_NO_ERROR) {
std::cerr << "OpenGL error before checking whether to call CopyDepthInfo: " << err << std::endl;
}
#endif
m_eventHandlers->CopyDepthInfo(renderTime, m_userData);
// Release the window's current context in case another Display wants to borrow it.
glfwMakeContextCurrent(nullptr);
}
// Wait until it is time to render the next frame. We must busy-wait here to avoid having our
// thread swapped out for longer than we want.
while (std::chrono::steady_clock::now() < m_impl->m_nextRenderTime) {
}
// Quit when our window closes.
if (glfwWindowShouldClose(Display::m_impl->m_window)) {
m_composite.reset();
m_status = "Done";
break;
}
// Process keyboard/mouse/joystick input events and update the viewpoint
//======================================
// Added by Sang Yoon to add key/joystick mappings for closing windows (Q or ESCAPE key on keyboard),
// resetting viewer's orientation (R key on keyboard or A key on Xbox controller),
// and pausing/resuming replaying (Left or Right trigger button on Xbox controller)
// Adding key mappings for closing windows
if (glfwGetKey(Display::m_impl->m_window, GLFW_KEY_Q) == GLFW_PRESS
|| glfwGetKey(Display::m_impl->m_window, GLFW_KEY_ESCAPE) == GLFW_PRESS) {
m_composite.reset();
m_status = "Done";
break;
}
// Adding key mapping for resetting viewer orientation
if (glfwGetKey(Display::m_impl->m_window, GLFW_KEY_R) == GLFW_PRESS) {
m_impl->m_rotationXDegrees = 0.0f;
m_impl->m_rotationZDegrees = 0.0f;
}
if (m_impl->m_glfwJoystickIndex >= 0) {
// Adding joystick button mapping for resetting viewer's orientation
int btnCount;
const unsigned char* btns = glfwGetJoystickButtons(m_impl->m_glfwJoystickIndex, &btnCount);
if (btnCount > 0) {
if (btns[0] == GLFW_PRESS) { // 0: A button, 1: B button, 2: X button, 3: Y button for Xbox Controller
m_impl->m_rotationXDegrees = 0.0f;
m_impl->m_rotationZDegrees = 0.0f;
}
}
// Adding joystick triggers mapping for pausing/resuming replaying
int axisCount;
const float* axes = glfwGetJoystickAxes(m_impl->m_glfwJoystickIndex, &axisCount);
bool triggerPressed = false;
float left_trigger = -1.0;
float right_trigger = -1.0;
if (axisCount >= 6) {
#ifdef WIN32
left_trigger = axes[4];
right_trigger = axes[5];
#else
// In Linux, the index number for the left trigger is different from that in Windows.
left_trigger = axes[2];
right_trigger = axes[5];
#endif
}
#ifdef WIN32
else if (axisCount >= 5) {
left_trigger = axes[4];
#else
else if (axisCount >= 3) {
left_trigger = axes[2];
#endif
}
if (left_trigger == 1.0 || right_trigger == 1.0)
triggerPressed = true;
if (triggerPressed && !m_impl->m_triggerPressed) {
if (m_eventHandlers && m_eventHandlers->ChangePlayPause) {
m_eventHandlers->ChangePlayPause(!m_nowPlaying, m_userData);
}
}
m_impl->m_triggerPressed = triggerPressed;
}
//======================================
HandleKeyboard();
HandleMouse();
if (m_impl->m_glfwJoystickIndex >= 0) {
auto now = std::chrono::steady_clock::now();
std::chrono::duration<double> elapsed = now - lastJoystickCheck;
lastJoystickCheck = now;
int axisCount;
const float* axes = glfwGetJoystickAxes(m_impl->m_glfwJoystickIndex, &axisCount);
if (axisCount >= 2) {
if (fabs(axes[0]) > 0.2) {
m_impl->m_rotationZDegrees -= 90.0f * elapsed.count() * axes[0];
}
if (fabs(axes[1]) > 0.2) {
m_impl->m_rotationXDegrees -= 90.0f * elapsed.count() * axes[1] * m_impl->m_joystickScaleY;
}
//======================================
// Added by Sang Yoon to add the right joystick mappings for viewer's orientation change
#ifdef WIN32
if (axisCount >= 4) {
float x_axis = axes[2];
float y_axis = axes[3];
#else
// In Linux, the index numbers for the right joystick are different from those in Windows.
if (axisCount >= 5) {
float x_axis = axes[3];
float y_axis = axes[4];
#endif
if (fabs(x_axis) > 0.2) {
m_impl->m_rotationZDegrees -= 90.0f * elapsed.count() * x_axis;
}
if (fabs(y_axis) > 0.2) {
m_impl->m_rotationXDegrees -= 90.0f * elapsed.count() * y_axis * m_impl->m_joystickScaleY;
}
}
//======================================
}
}
// Ensure that the view orientation stays within bounds.
ComputeAndClampViewOrientation();
// Handle any window resizing
SetViewportSizeAndFOVs(m_impl->m_views[0]);
// Trigger the cameras, saying that we need the data now. The base class will handle offsetting
// by the specified transmission/processing time as passed to its constructor by the client.
TriggerCameras(std::chrono::steady_clock::now());
// Record the render start time if we have a place to put it.
if (m_timingInfo) {
m_timingInfo->renderStartTimes.push_back(std::chrono::steady_clock::now());
}
// Grab the context mutex for the duration of the loop. Once we have it, we know
// that the context is not active in another thread.
// Make the window's context current.
// DO NOT do any GLFW calls while holding the context -- it causes rare hangs on Linux.
std::lock_guard<std::mutex> lock(Display::m_impl->m_contextMutex);
glfwMakeContextCurrent(Display::m_impl->m_window);
m_composite->Render(renderTime, m_impl->m_views);
// Record the render submit time if we have a place to put it.
if (m_timingInfo) {
m_timingInfo->renderSubmitTimes.push_back(std::chrono::steady_clock::now());
}
// Swap front and back buffers and wait for it to complete, then compute the next frame time.
glfwSwapBuffers(Display::m_impl->m_window);
glFinish();
m_impl->m_nextRenderTime = std::chrono::steady_clock::now() +
std::chrono::microseconds(static_cast<long long>(1e6/fps) - renderAheadMicroseconds);
m_impl->m_nextDepthTime = m_impl->m_nextRenderTime - std::chrono::microseconds(m_depthAheadMicroseconds);
// Half way through the next frame, which is when we want the geometry adjusted for.
m_impl->m_nextFrameTime = std::chrono::steady_clock::now() +
std::chrono::microseconds(static_cast<long long>(1e6/fps)*3/2);
// Release the window's current context in case another Display wants to borrow it.
glfwMakeContextCurrent(nullptr);
}
// Done with the window
glfwDestroyWindow(Display::m_impl->m_window);
}
void DisplayWindow::SetNowPlaying(bool nowPlaying)
{
// Call the parent-class method to set the now-playing state.
Display::SetNowPlaying(nowPlaying);
// Set the pause time based on whether we are now playing so that
// we don't extrapolate forward in time while paused.
if (!m_nowPlaying) {
m_pauseTime = std::make_unique<Time>();
m_timer->GetCoreTime(*m_pauseTime, std::chrono::steady_clock::now());
} else {
m_pauseTime.reset();
}
}
void DisplayWindow::HandleKeyboard()
{
// See how long it has been since the last keyboard check. If there has not been one,
// then set the last check time to now and return.
if (m_impl->m_lastKeyboardCheck == std::chrono::steady_clock::time_point()) {
m_impl->m_lastKeyboardCheck = std::chrono::steady_clock::now();
return;
}
auto now = std::chrono::steady_clock::now();
std::chrono::duration<double> elapsed = now - m_impl->m_lastKeyboardCheck;
m_impl->m_lastKeyboardCheck = now;
double DegreesPerSecond = 30.0;
// Rotate to look up when the up key is pressed
if (glfwGetKey(Display::m_impl->m_window, GLFW_KEY_UP) == GLFW_PRESS) {
m_impl->m_rotationXDegrees += DegreesPerSecond * elapsed.count();
}
// Rotate to look down when the down key is pressed
if (glfwGetKey(Display::m_impl->m_window, GLFW_KEY_DOWN) == GLFW_PRESS) {
m_impl->m_rotationXDegrees -= DegreesPerSecond * elapsed.count();
}
// Rotate to look right when the right key is pressed
if (glfwGetKey(Display::m_impl->m_window, GLFW_KEY_RIGHT) == GLFW_PRESS) {
m_impl->m_rotationZDegrees -= DegreesPerSecond * elapsed.count();
}
// Rotate to look left when the left key is pressed
if (glfwGetKey(Display::m_impl->m_window, GLFW_KEY_LEFT) == GLFW_PRESS) {
m_impl->m_rotationZDegrees += DegreesPerSecond * elapsed.count();
}
// Toggle play/pause when the space key is pressed (once per press/release cycle).
bool spacePressed = (glfwGetKey(Display::m_impl->m_window, GLFW_KEY_SPACE) == GLFW_PRESS);
if (spacePressed && !m_impl->m_spacePressed) {
if (m_eventHandlers && m_eventHandlers->ChangePlayPause) {
m_eventHandlers->ChangePlayPause(!m_nowPlaying, m_userData);
}
}
m_impl->m_spacePressed = spacePressed;
// Toggle depth computation when the 'd' key is pressed (once per press/release cycle).
bool dPressed = (glfwGetKey(Display::m_impl->m_window, GLFW_KEY_D) == GLFW_PRESS);
if (dPressed && !m_impl->m_dPressed) {
m_impl->m_displayingDepth = !m_impl->m_displayingDepth;
if (m_eventHandlers && m_eventHandlers->SetToRenderDepth) {
m_eventHandlers->SetToRenderDepth(m_impl->m_displayingDepth, m_userData);
}
}
m_impl->m_dPressed = dPressed;
// Adjust the active camera index when the '[' or ']' keys are pressed.
bool leftBracketPressed = (glfwGetKey(Display::m_impl->m_window, GLFW_KEY_LEFT_BRACKET) == GLFW_PRESS);
if (leftBracketPressed && !m_impl->m_leftBracketPressed) {
if (m_eventHandlers && m_eventHandlers->DecrementActiveCamera) {
m_eventHandlers->DecrementActiveCamera(m_userData);
}
}
m_impl->m_leftBracketPressed = leftBracketPressed;
bool rightBracketPressed = (glfwGetKey(Display::m_impl->m_window, GLFW_KEY_RIGHT_BRACKET) == GLFW_PRESS);
if (rightBracketPressed && !m_impl->m_rightBracketPressed) {
if (m_eventHandlers && m_eventHandlers->IncrementActiveCamera) {
m_eventHandlers->IncrementActiveCamera(m_userData);
}
}
m_impl->m_rightBracketPressed = rightBracketPressed;
// Adjust the camera offset for the active camera while the '-' (decrement) or '=' (increment) keys are pressed.
bool minusPressed = (glfwGetKey(Display::m_impl->m_window, GLFW_KEY_MINUS) == GLFW_PRESS);
bool equalPressed = (glfwGetKey(Display::m_impl->m_window, GLFW_KEY_EQUAL) == GLFW_PRESS);
int increment = 0;
if (minusPressed) {
increment = -1;
} else if (equalPressed) {
increment = 1;
}
if (increment != 0) {
if (m_eventHandlers && m_eventHandlers->AdjustActiveCameraOffset) {
m_eventHandlers->AdjustActiveCameraOffset(increment, m_userData);
}
}
// Adjust the camera gain for the active camera while the ',' (decrement) or '.' (increment) keys are pressed.
bool periodPressed = (glfwGetKey(Display::m_impl->m_window, GLFW_KEY_PERIOD) == GLFW_PRESS);
bool commaPressed = (glfwGetKey(Display::m_impl->m_window, GLFW_KEY_COMMA) == GLFW_PRESS);
float incrementGain = 1;
if (periodPressed) {
incrementGain *= 1.001f;
} else if (commaPressed) {
incrementGain /= 1.001f;
}
if (incrementGain != 1) {
if (m_eventHandlers && m_eventHandlers->AdjustActiveCameraGain) {
m_eventHandlers->AdjustActiveCameraGain(incrementGain, m_userData);
}
}
bool gPressed = (glfwGetKey(Display::m_impl->m_window, GLFW_KEY_G) == GLFW_PRESS);
if (gPressed && !m_impl->m_gPressed) {
if (m_eventHandlers && m_eventHandlers->AutoUpdateColorOffsetsAndGains) {
m_eventHandlers->AutoUpdateColorOffsetsAndGains(m_userData);
}
}
m_impl->m_gPressed = gPressed;
bool oPressed = (glfwGetKey(Display::m_impl->m_window, GLFW_KEY_O) == GLFW_PRESS);
if (oPressed && !m_impl->m_oPressed) {
if (m_eventHandlers && m_eventHandlers->AutoUpdateColorOffsets) {
m_eventHandlers->AutoUpdateColorOffsets(m_userData);
}
}
m_impl->m_oPressed = oPressed;
// If the 's' key is pressed, send an event asking to save the current configuration file.
bool sPressed = (glfwGetKey(Display::m_impl->m_window, GLFW_KEY_S) == GLFW_PRESS);
if (sPressed && !m_impl->m_sPressed) {
if (m_eventHandlers && m_eventHandlers->SaveCameraConfig) {
m_eventHandlers->SaveCameraConfig("adjusted_camera_config.json", m_userData);
}
}
m_impl->m_sPressed = sPressed;
// If the 'c' key is pressed, toggle the display of camera names.
bool cPressed = (glfwGetKey(Display::m_impl->m_window, GLFW_KEY_C) == GLFW_PRESS);
if (cPressed && !m_impl->m_cPressed) {
m_showCameraNames = !m_showCameraNames;
if (m_eventHandlers && m_eventHandlers->ShowCameraNames) {
m_eventHandlers->ShowCameraNames(m_showCameraNames, m_userData);
}
}
m_impl->m_cPressed = cPressed;
// If the 'a' key is pressed, reset the analysis connections.
bool aPressed = (glfwGetKey(Display::m_impl->m_window, GLFW_KEY_A) == GLFW_PRESS);
if (aPressed && !m_impl->m_aPressed) {
if (m_eventHandlers && m_eventHandlers->ResetAnalysis) {
m_eventHandlers->ResetAnalysis(m_userData);
}
}
m_impl->m_aPressed = aPressed;
}
void DisplayWindow::HandleMouse()
{
// If the mouse button has not been pressed and it now is pressed, set the mouse pressed
// position to the current position.
if (!m_impl->m_leftMouseButtonPressed && (glfwGetMouseButton(Display::m_impl->m_window, GLFW_MOUSE_BUTTON_LEFT) == GLFW_PRESS)) {
m_impl->m_leftMouseButtonPressed = true;
glfwGetCursorPos(Display::m_impl->m_window, &m_impl->m_mousePressedX, &m_impl->m_mousePressedY);
m_impl->m_lastMouseMotion = std::chrono::steady_clock::now();
return;
}
// If the mouse button is not now pressed, clear the pressed flag and we're done.
if (glfwGetMouseButton(Display::m_impl->m_window, GLFW_MOUSE_BUTTON_LEFT) != GLFW_PRESS) {
m_impl->m_leftMouseButtonPressed = false;
return;
}
// Find the current mouse position and delta from the pressed position. Scale by half the window height
// and the maximum rate and the time in seconds and adjust the viewpoint accordingly.
double xpos, ypos;
glfwGetCursorPos(Display::m_impl->m_window, &xpos, &ypos);
double deltaX = xpos - m_impl->m_mousePressedX;
double deltaY = ypos - m_impl->m_mousePressedY;
// Scale the deltas to be a fraction of half the window height (scale them both by the same amount).
int width, height;
glfwGetWindowSize(Display::m_impl->m_window, &width, &height);
deltaX /= (height / 2.0);
deltaY /= (height / 2.0);
auto now = std::chrono::steady_clock::now();
std::chrono::duration<double> elapsed = now - m_impl->m_lastMouseMotion;
m_impl->m_lastMouseMotion = now;
// Handle the mouse movement with the button held down
// We scale the deltas and increment the rotation angles so long as the button is held down.
double MaxDegreesPerSecond = 45.0;
m_impl->m_rotationZDegrees -= MaxDegreesPerSecond * deltaX * elapsed.count();
m_impl->m_rotationXDegrees -= MaxDegreesPerSecond * deltaY * elapsed.count();
}
void DisplayWindow::ComputeAndClampViewOrientation()
{
// Clamp the rotation angles to reasonable values.
if (m_impl->m_rotationXDegrees > 60.0) {
m_impl->m_rotationXDegrees = 60.0;
}
if (m_impl->m_rotationXDegrees < -60.0) {
m_impl->m_rotationXDegrees = -60.0;
}
if (m_impl->m_rotationZDegrees > 120.0) {
m_impl->m_rotationZDegrees = 120.0;
}
if (m_impl->m_rotationZDegrees < -120.0) {
m_impl->m_rotationZDegrees = -120.0;
}
// Compute the orientation Quarternion by building two different rotation
// matrices and applying them in the correct order.
float rotationZRadians = glm::radians(m_impl->m_rotationZDegrees);
float rotationXRadians = glm::radians(m_impl->m_rotationXDegrees);
// Create rotation matrices
// Combine the rotations: first Z, then X
/// @todo Consider doing this with just quaternions and axis-angles.
glm::mat4 rotationZ = glm::rotate(glm::mat4(1.0f), rotationZRadians, glm::vec3(0.0f, 0.0f, 1.0f));
glm::mat4 rotationX = glm::rotate(rotationZ, rotationXRadians, glm::vec3(1.0f, 0.0f, 0.0f));
glm::mat4 combinedRotation = rotationX;
// Decompose the combined rotation matrix to get the quaternion.
glm::vec3 scale, translation, skew;
glm::vec4 perspective;
glm::quat orientation;
glm::decompose(combinedRotation, scale, orientation, translation, skew, perspective);
// Store the quaternion.
m_impl->m_views[0].orientation[0] = orientation.w;
m_impl->m_views[0].orientation[1] = orientation.x;
m_impl->m_views[0].orientation[2] = orientation.y;
m_impl->m_views[0].orientation[3] = orientation.z;
}
//==============================================================================
// Structures and methods for DisplayTexture class.
/// @brief Implementation details for the DisplayTexture class to hide #includes from users of the DisplayTexture class.
class asdp::render::DisplayTexture::DisplayTextureImpl {
public:
// Nothing here, we re-use base-class objects for everything we need.
};
DisplayTexture::DisplayTexture(Display* sharedWindow)
: Display(std::shared_ptr<CompositeCube>(), std::shared_ptr<CoreClient>(), 0, 0, 0)
, m_impl(new DisplayTextureImpl)
{
{
// Hold the window mutex so that only one window can be created at a time.
std::lock_guard<std::mutex> windowLock(m_windowMutex);
// Set the window to be hidden.
glfwWindowHint(GLFW_VISIBLE, false);
// Construct our context, borrowing the context of the shared window so that it will be
// active on our context (required for Windows).
GLFWwindow* windowToShare = nullptr;
if (sharedWindow != nullptr) {
if (!sharedWindow->BorrowContext()) {
m_status = "Failed to borrow context from shared window";
return;
}
windowToShare = sharedWindow->m_impl->m_window;
}
Display::m_impl->m_window = glfwCreateWindow(100, 100, "", nullptr, windowToShare);
if (sharedWindow != nullptr) {
if (!sharedWindow->ReturnContext()) {
m_status = "Failed to return context to shared window";
return;
}
}
}
// Verify that the window was created.
if (!Display::m_impl->m_window) {
m_status = "Failed to create GLFW window";
return;
}
// Grab the context mutex for the duration of the setup. Once we have it, we know
// that the context is not active in another thread.
// Make the window's context current.
// DO NOT do any GLFW calls while holding the context -- it causes rare hangs on Linux.
std::lock_guard<std::mutex> lock(Display::m_impl->m_contextMutex);
glfwMakeContextCurrent(Display::m_impl->m_window);
// Initialize GLEW in our context. It is okay to initialize it more than once.
glewExperimental = true;
if (glewInit() != GLEW_OK) {
m_status = "Failed to initialize GLEW";
return;
}
// Clear any GL error that Glew caused. Apparently on Non-Windows
// platforms, this can cause a spurious error 1280.
glGetError();
// Release the window's current context in case another Display wants to borrow it.
glfwMakeContextCurrent(nullptr);