-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathASDP_Render_Module.cpp
More file actions
2893 lines (2646 loc) · 131 KB
/
Copy pathASDP_Render_Module.cpp
File metadata and controls
2893 lines (2646 loc) · 131 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
*/
// This is a client that connects to the first server it encounters and runs a Render Module.
/**
* @file ASDP_Render_Module.cpp
* @brief Apache Strap-Down Pilotage Render Module.
*
* @author ReliaSolve.
* @date May 20th, 2024.
*/
#include <iostream>
#include <fstream>
#include <sstream>
#include <chrono>
#include <map>
#include <set>
#include <mutex>
#include <thread>
#include <string>
#include <filesystem>
#include <vector>
#include <list>
#include <atomic>
#include <memory>
#include <algorithm>
#include <ASDP_Core_API.h>
#include <ASDP_SpinFreeQueue.hpp>
#include <ASDP_BufferPool.h>
#include <ASDP_ClockSynchronizer.h>
#include "CUDABufferPool.h"
#include <nlohmann/json.hpp>
#include <GL/glew.h>
#include <ToneMap.h>
#include <RenderTimingInfo.h>
#include <CameraRenderInfo.h>
#include <Composite.h>
#include <Display.h>
#include <CPUDataToTextureHandler.h>
#include <PoseAdjuster.h>
#include <DepthEstimator.h>
#include <ImageStatistics.h>
#include <RangeEstimator.h>
#include <Calibration_Helpers.h>
#include <PointCorrespondences.h>
#include <Analysis.h>
#include <cuda.h>
#include <cuda_runtime.h>
#include <cuda_gl_interop.h>
using namespace asdp;
using namespace asdp::render;
using namespace asdp::analysis;
using json = nlohmann::json;
static std::string VERSION = "3.35.0";
/// @brief The path to the configuration file. Defined in the CMakeLists file.
std::filesystem::path g_dirPath = CONFIG_FILE_PATH;
/// @brief Structure storing information needed by the callback handlers, a pointer is passeed in userData.
struct CallbackHandlerData {
std::string cameraConfigFileName; ///< The name of the configuration file that was read and parsed.
std::atomic_int analysisEpoch{ 0 }; ///< The current epoch of the analysis data, incremented to reset analysis.
};
static CallbackHandlerData g_callbackHandlerData;
/// @brief Global variable set by callback handlers to tell when we're playing and pausing.
static std::atomic<bool> g_paused(false);
/// @brief Global variable to hold the timing information for the program.
static asdp::render::RenderTimingInfo g_timingInfo;
/// @brief Global variable to hold the depth estimator.
static std::shared_ptr<DepthEstimator> g_depthEstimator;
/// @brief Global variables to hold the visible and depth cameras.
static std::vector< std::shared_ptr<asdp::render::CameraRenderInfo> > g_visibleCameras, g_depthCameras;
/// @brief Global variable to hold the index of the active camera.
static std::atomic<size_t> g_activeCameraIndex(0);
/// @brief Global variable to hold the composite cameras.
static std::shared_ptr<CompositeCameras> g_composite;
/// @brief Global variable to hold the display used to provide a context for point correspondences.
static std::shared_ptr<Display> g_pointCorrespondenceDisplay;
/// @brief Global variable to hold the point correspondences object.
static std::shared_ptr<PointCorrespondences> g_pointCorrespondences;
/// @brief Vector of camera pairs to use for auto-updating color offsets.
/// @todo Eventually, this should be determined from the geometry of the camera configuration.
static std::vector< std::array<uint32_t, 2> > g_cameraPairs = {
{11, 14}, {14, 17}, {17, 20}, // Right along the center row
{11, 8}, {8, 5}, {5, 2}, // Left along the center row
{2, 1}, {5, 4}, {8, 7}, {11, 10}, {14, 13}, {17, 16}, {20, 19}, // Top row
{2, 3}, {5, 6}, {8, 9}, {11, 12}, {14, 15}, {17, 18}, {20, 21} // Bottom row
};
/// @brief Atomic shared pointer to a map from name to the current and past history of active objects.
/// Filled in by the Analysis API reading thread and used by the annotation callback.
static std::shared_ptr< std::map<std::string, AnalysisObjectOverTime> > g_currentAnalysis;
static float g_analysisFadeTimeSeconds = 1.0f; ///< Time in seconds for analysis annotations to fade out.
static float g_analysisChanceThreshold = 0.0f; ///< Minimum chance threshold for analysis annotations to be shown.
static std::atomic<Time> g_lastCLOCK_SYNC = { 0 }; ///< The last CLOCK_SYN message time received, used to adjust analysis displays
static_assert(std::is_trivially_copyable<Time>::value, "Time must be trivially copyable to use std::atomic<Time> portably");
/// @brief Vector of Annotation objects to hold camera annotations if they are shown.
static std::vector<CompositeCameras::Annotation> g_cameraAnnotations;
/// @brief Atomic boolean to control the analysis thread.
static std::atomic_bool g_runAnalysisThread;
/// @brief Mutex to protect access to the current annotations.
static std::mutex g_annotationMutex;
/// @brief Atomic boolean to control the depth thread.
static std::atomic_bool g_runDepthThread;
/// @brief Thread for running depth estimation.
static std::thread g_depthThread;
/// @brief Callback handler to increment the active camera index.
static void IncrementActiveCamera(void* /* unused */)
{
g_activeCameraIndex++;
if (g_activeCameraIndex >= g_visibleCameras.size()) {
g_activeCameraIndex = 0;
}
std::cout << "Incremented active camera index to " << g_activeCameraIndex.load();
if (g_activeCameraIndex < g_visibleCameras.size()) {
std::cout << " (ID = " << g_visibleCameras[g_activeCameraIndex]->m_ID << ")";
}
std::cout << std::endl;
}
/// @brief Callback handler to decrement the active camera index.
static void DecrementActiveCamera(void* /* unused */)
{
if (g_activeCameraIndex == 0) {
g_activeCameraIndex = g_visibleCameras.size() - 1;
} else {
g_activeCameraIndex--;
}
std::cout << "Decremented active camera index to " << g_activeCameraIndex.load();
if (g_activeCameraIndex < g_visibleCameras.size()) {
std::cout << " (ID = " << g_visibleCameras[g_activeCameraIndex]->m_ID << ")";
}
std::cout << std::endl;
}
/// @brief Callback handler to toggle play and pause.
static void ChangePlayPause(bool nowPlaying, void* /* unused */)
{
g_paused = !nowPlaying;
std::cout << "Toggled play/pause to: " << (g_paused ? "paused" : "playing") << std::endl;
}
/// @brief Callback handler to toggle showing camera names.
static void ShowCameraNames(bool showNames, void* /* unused */)
{
std::lock_guard<std::mutex> lock(g_annotationMutex);
g_cameraAnnotations.clear();
if (showNames) {
CompositeCameras::Annotation annotation;
annotation.uv = { 0.5, 0.5 }; // Center of the image
annotation.color = { 1.0f, 1.0f, 0.0f, 1.0f }; // Yellow and fully opaque
for (auto const& cameraRenderInfo : g_visibleCameras) {
annotation.cameraID = cameraRenderInfo->m_ID;
annotation.label = "CamID: " + std::to_string(cameraRenderInfo->m_ID);
g_cameraAnnotations.push_back(annotation);
}
}
std::cout << "Toggled camera names to: " << (showNames ? "shown" : "hidden") << std::endl;
}
/// @brief Adjust the active camera's color offset calibration value.
/// @param offsetDelta The amount to add to the offset, positive or negative.
static void AdjustActiveCameraOffset(int offsetDelta, void* /* unused */)
{
if (g_activeCameraIndex >= g_visibleCameras.size()) {
std::cerr << "Error: Active camera index out of range." << std::endl;
return;
}
std::shared_ptr<asdp::render::CameraRenderInfo> cri = g_visibleCameras[g_activeCameraIndex];
if (cri == nullptr) {
std::cerr << "Error: Active camera is null." << std::endl;
return;
}
// Adjust the color offset and gain.
float currentOffset, currentGain;
cri->GetColorOffsetGain(currentOffset, currentGain);
cri->SetColorOffsetGain(currentOffset + offsetDelta, currentGain);
std::cout << "Adjusted camera ID " << cri->m_ID << " color offset to : " << currentOffset + offsetDelta << std::endl;
}
/// @brief Adjust the active camera's color gain calibration value.
/// @param gainDelta The amount to multiply the gain by, <1 or >1.
static void AdjustActiveCameraGain(float gainDelta, void* /* unused */)
{
if (g_activeCameraIndex >= g_visibleCameras.size()) {
std::cerr << "Error: Active camera index out of range." << std::endl;
return;
}
std::shared_ptr<asdp::render::CameraRenderInfo> cri = g_visibleCameras[g_activeCameraIndex];
if (cri == nullptr) {
std::cerr << "Error: Active camera is null." << std::endl;
return;
}
// Adjust the color offset and gain.
float currentOffset, currentGain;
cri->GetColorOffsetGain(currentOffset, currentGain);
cri->SetColorOffsetGain(currentOffset, currentGain * gainDelta);
std::cout << "Adjusted camera ID " << cri->m_ID << " color gain to : " << currentGain * gainDelta << std::endl;
}
static double TimeDiffMagnitude(asdp::Time t1, asdp::Time t2)
{
asdp::Time diff;
if (t1 > t2) {
diff = t1 - t2;
} else {
diff = t2 - t1;
}
return diff.seconds + diff.microseconds * 1.0e-6;
}
/// @brief Get a consistent set of images from all visible cameras for color offset adjustment.
/// @return Vector of shared pointers to ImageData objects, one from each visible camera. The
/// caller is responsible for unlocking the images when done using them by calling
/// UnlockConsistentImageSet() and passing it this return vector.
/// Note: If not enough images are available, an empty vector is returned.
static std::vector< std::shared_ptr<ImageData> > GetConsistentImageSet()
{
std::vector< std::shared_ptr<ImageData> > imageSet;
// Pull the first two images from each queue and then select a set of consistent ones.
std::vector< std::list< std::shared_ptr<ImageData> > > images;
for (auto const& cameraRenderInfo : g_visibleCameras) {
images.push_back(cameraRenderInfo->m_imageQueue->LockNewestImages(2));
if (images.back().size() != 2) {
std::cerr << "GetConsistentImageSet(): Could not get all needed images, skipping frame" << std::endl;
return imageSet;
}
}
// Find the time of the oldest image among the first (newest) image from
// all cameras and then selecting from each pair the one whose time is closest to the
// selected time.
asdp::Time desiredTime = images[0].front()->imageCenterTime;
for (size_t i = 1; i < images.size(); i++) {
if (images[i].front()->imageCenterTime < desiredTime) {
desiredTime = images[i].front()->imageCenterTime;
}
}
// Find the image from each list that is closest to the desired time. Push it into the m_images
// array and return the other images+/ to the queue.
for (size_t i = 0; i < images.size(); i++) {
auto& imList = images[i];
auto best = imList.begin();
double bestDiff = TimeDiffMagnitude((*best)->imageCenterTime, desiredTime);
for (auto it = imList.begin(); it != imList.end(); ++it) {
double diff = TimeDiffMagnitude((*it)->imageCenterTime, desiredTime);
if (diff < bestDiff) {
best = it;
bestDiff = diff;
}
}
for (auto it = imList.begin(); it != imList.end(); ++it) {
if (it == best) {
// Use this image
imageSet.push_back(*it);
} else {
// Unlock the images that are not selected.
g_visibleCameras[i]->m_imageQueue->UnlockImage(*it);
}
}
}
return imageSet;
}
/// @brief Unlock a consistent set of images previously obtained by calling GetConsistentImageSet().
/// @param imageSet The vector of shared pointers to ImageData objects obtained from GetConsistentImageSet().
static void UnlockConsistentImageSet(const std::vector< std::shared_ptr<ImageData> >& imageSet)
{
for (size_t i = 0; i < imageSet.size(); i++) {
g_visibleCameras[i]->m_imageQueue->UnlockImage(imageSet[i]);
}
}
/// @brief Make a vector of pairs of pixel values, one from each image, read at the specified correspondence locations.
/// @param correspondences Locations from first and second image to read.
/// @param widths Array of 2 image widths.
/// @param heights Array of 2 image heights.
/// @param imageData Array of 2 images to read data from.
static std::vector< std::array<uint16_t, 2> > GetRawPixelValues(
const std::vector<PointCorrespondences::PointPair>& correspondences,
std::array<uint16_t, 2> widths, std::array<uint16_t, 2> heights,
std::array< std::shared_ptr<ImageData>, 2> imageData)
{
// Borrow the OpenGL context so that we can read back the pixel values.
if (!g_pointCorrespondenceDisplay || !g_pointCorrespondenceDisplay->BorrowContext()) {
std::cerr << "GetRawPixelValues(): Error: Could not borrow OpenGL context." << std::endl;
return {};
}
// Read back both images from texture memory to CPU memory. These have already been adjusted by
// the offset and gain on the way to being written to the texture.
std::array<std::vector<uint16_t>, imageData.size()> imagePixels;
GLenum ret;
for (int i = 0; i < imagePixels.size(); i++) {
imagePixels[i].resize(widths[i] * heights[i]);
glBindTexture(GL_TEXTURE_2D, imageData[i]->texture);
glGetTexImage(GL_TEXTURE_2D, 0, GL_RED, GL_UNSIGNED_SHORT, imagePixels[i].data());
#if !defined(NDEBUG)
ret = glGetError();
if (ret != GL_NO_ERROR) {
std::cerr << "GetRawPixelValues(): Error: glGetTexImage() failed for image " << i
<< " with error code " << ret << std::endl;
glBindTexture(GL_TEXTURE_2D, 0);
g_pointCorrespondenceDisplay->ReturnContext();
return {};
}
#endif
}
glBindTexture(GL_TEXTURE_2D, 0);
// Return the OpenGL context.
if (!g_pointCorrespondenceDisplay || !g_pointCorrespondenceDisplay->ReturnContext()) {
std::cerr << "GetRawPixelValues(): Error: Could not return OpenGL context." << std::endl;
return {};
}
// Construct the vector of pixel value pairs, rounding each pixel location to the nearest pixel
// location and clamping to ensure we don't read out of bounds.
std::vector< std::array<uint16_t, imageData.size()> > rawPixels;
for (const auto& pair : correspondences) {
std::array<uint16_t, imageData.size()> pixelValues;
for (int i = 0; i < imageData.size(); i++) {
// Compute the pixel location, rounding to nearest integer and clamping to image bounds.
int x = static_cast<int>(std::round(pair[i][0]));
int y = static_cast<int>(std::round(pair[i][1]));
if (x < 0) { x = 0; }
if (x >= widths[i]) { x = widths[i] - 1; }
if (y < 0) { y = 0; }
if (y >= heights[i]) { y = heights[i] - 1; }
// Read the pixel value.
pixelValues[i] = imagePixels[i][y * widths[i] + x];
}
rawPixels.emplace_back(pixelValues);
}
return rawPixels;
}
/// @brief Compute the color offset adjustment needed for the second camera in a pair based on the first.
/// @param correspondences The point correspondences between the two cameras.
/// @param imageData1 The image data for the first camera.
/// @param imageData2 The image data for the second camera.
/// @param cri1 The camera render info for the first camera.
/// @param cri2 The camera render info for the second camera.
/// @return The new color offset for the second camera that will make the adjusted average pixel values
/// for both cameras match.
static float ComputeNewColorOffset(
const std::vector<PointCorrespondences::PointPair>& correspondences,
std::shared_ptr<ImageData> imageData1, std::shared_ptr<ImageData> imageData2,
std::shared_ptr<asdp::render::CameraRenderInfo> cri1, std::shared_ptr<asdp::render::CameraRenderInfo> cri2)
{
// Read the vector of raw values from both images, which we'll adjust and then use to compute
// the new offset.
std::array<uint16_t, 2> widths= { cri1->m_resolutionPixels[0], cri2->m_resolutionPixels[0] };
std::array<uint16_t, 2> heights = { cri1->m_resolutionPixels[1], cri2->m_resolutionPixels[1] };
std::array<std::shared_ptr<ImageData>, 2> imageDatas = {imageData1, imageData2 };
std::vector< std::array<uint16_t, 2> > rawPixels = GetRawPixelValues(correspondences,
widths, heights, imageDatas);
// Find the average pixel value for each camera after adjusting for gain and offset.
float offset1, gain1, offset2, gain2;
cri1->GetColorOffsetGain(offset1, gain1);
cri2->GetColorOffsetGain(offset2, gain2);
double sum1 = 0.0, sum2 = 0.0;
for (const auto& pixelPair : rawPixels) {
sum1 += (pixelPair[0] + offset1) * gain1;
sum2 += (pixelPair[1] + offset2) * gain2;
}
float avg1 = sum1 / rawPixels.size();
float avg2 = sum2 / rawPixels.size();
// Compute the new offset for the second camera to make its average match the first camera's average.
// We want to know how much and in which direction to shift the second camera's pixel values. The
// second camera's offset is what is added to the raw pixel values before gain is applied, so we need to
// subtract the needed delta divided by the gain from the current offset.
float delta = avg2 - avg1;
float newOffset2 = offset2 - (delta / gain2);
return newOffset2;
}
static void AutoUpdateColorOffsets(void* /* unused */)
{
if (!g_pointCorrespondences) {
std::cerr << "AutoUpdateColorOffsets(): Error: No point correspondences object available." << std::endl;
return;
}
// Get a consistent set of images to use for the adjustment.
std::vector< std::shared_ptr<ImageData> > imageSet = GetConsistentImageSet();
if (imageSet.size() != g_visibleCameras.size()) {
UnlockConsistentImageSet(imageSet);
std::cerr << "AutoUpdateColorOffsets(): Error: Could not get consistent image set." << std::endl;
return;
}
// Update the color offsets on the second of each camera pair based on the first. Pass the appropriate
// image pair along with the image infos.
// image pair along with the image infos.
for (const auto& cameraPair : g_cameraPairs) {
std::vector<PointCorrespondences::PointPair> correspondences =
g_pointCorrespondences->CorrespondencesForCameraPair(cameraPair);
if (correspondences.empty()) {
std::cerr << "Warning: No correspondences found for camera pair: ("
<< cameraPair[0] << ", " << cameraPair[1] << "), skipping color adjustment" << std::endl;
continue;
}
// Find the indices of the entries in g_visibleCameras whose camID fields match the two cameras in the pair.
size_t index1 = SIZE_MAX, index2 = SIZE_MAX;
for (size_t i = 0; i < g_visibleCameras.size(); i++) {
if (g_visibleCameras[i]->m_ID == cameraPair[0]) {
index1 = i;
}
if (g_visibleCameras[i]->m_ID == cameraPair[1]) {
index2 = i;
}
}
if (index1 == SIZE_MAX || index2 == SIZE_MAX) {
std::cerr << "Warning: One or both cameras not found for camera pair: ("
<< cameraPair[0] << ", " << cameraPair[1] << "), skipping color adjustment" << std::endl;
continue;
}
// Compute the offset adjustment needed.
float newOffset = ComputeNewColorOffset(correspondences,
imageSet[index1], imageSet[index2],
g_visibleCameras[index1], g_visibleCameras[index2]);
// Apply the offset adjustment to the second camera in the pair.
std::shared_ptr<asdp::render::CameraRenderInfo> cri = g_visibleCameras[index2];
float currentOffset, currentGain;
cri->GetColorOffsetGain(currentOffset, currentGain);
cri->SetColorOffsetGain(newOffset, currentGain);
}
// Done with the images, unlock them.
UnlockConsistentImageSet(imageSet);
}
/// @brief Compute the color offset adjustment needed for the second camera in a pair based on the first.
/// @param correspondences The point correspondences between the two cameras.
/// @param imageData1 The image data for the first camera.
/// @param imageData2 The image data for the second camera.
/// @param cri1 The camera render info for the first camera.
/// @param cri2 The camera render info for the second camera.
/// @return The new color offset for the second camera that will make the adjusted average pixel values
/// for both cameras match.
static std::array<float, 2> ComputeNewColorOffsetGain(
const std::vector<PointCorrespondences::PointPair>& correspondences,
std::shared_ptr<ImageData> imageData1, std::shared_ptr<ImageData> imageData2,
std::shared_ptr<asdp::render::CameraRenderInfo> cri1, std::shared_ptr<asdp::render::CameraRenderInfo> cri2)
{
// Read the vector of raw values from both images, which we'll adjust and then use to compute
// the new offset.
std::array<uint16_t, 2> widths = { cri1->m_resolutionPixels[0], cri2->m_resolutionPixels[0] };
std::array<uint16_t, 2> heights = { cri1->m_resolutionPixels[1], cri2->m_resolutionPixels[1] };
std::array<std::shared_ptr<ImageData>, 2> imageDatas = { imageData1, imageData2 };
std::vector< std::array<uint16_t, 2> > rawPixels = GetRawPixelValues(correspondences,
widths, heights, imageDatas);
// Transform the points to consistent space based on the current offset and gain and place them
// into a vector of 2D points where the first element (x) is from the first camera and the second
// element (y) is from the second camera.
float offset1, gain1, offset2, gain2;
cri1->GetColorOffsetGain(offset1, gain1);
cri2->GetColorOffsetGain(offset2, gain2);
std::vector<PointCorrespondences::Point2D> adjustedPoints;
for (const auto& pixelPair : rawPixels) {
PointCorrespondences::Point2D adjustedPoint;
adjustedPoint[0] = (pixelPair[0] + offset1) * gain1;
adjustedPoint[1] = (pixelPair[1] + offset2) * gain2;
adjustedPoints.push_back(adjustedPoint);
}
// Compute the best-fit line through the points.
float sumX = 0.0f, sumY = 0.0f, sumXY = 0.0f, sumXX = 0.0f;
for (const auto& pt : adjustedPoints) {
sumX += pt[0];
sumY += pt[1];
sumXY += pt[0] * pt[1];
sumXX += pt[0] * pt[0];
}
float n = static_cast<float>(adjustedPoints.size());
float slope = (n * sumXY - sumX * sumY) / (n * sumXX - sumX * sumX);
float intercept = (sumY - slope * sumX) / n;
// Compute the factor to adjust the slope by to make it 1.0 (i.e., y = x).
// This is the amount by which we'll multiply the gain of the second camera to bring it into alignment.
// If the slope is very different, just leave the gain unchanged because this is
// probably due to numerical instability.
/// @todo Consider a more robust way to determine numerical instability.
float gainAdjustment = 1.0f / slope;
if (slope < 0.5 || slope > 2) { gainAdjustment = 1.0f; }
float newGain2 = gain2 * gainAdjustment;
// Compute the new point values with the adjusted gain for the second camera to find the new offset needed.
for (size_t i = 0; i < adjustedPoints.size(); i++) {
adjustedPoints[i][1] = (rawPixels[i][1] + offset2) * newGain2;
}
// Find the average pixel value for each camera in the adjusted point set.
float sum1 = 0.0, sum2 = 0.0;
for (const auto& pt : adjustedPoints) {
sum1 += pt[0];
sum2 += pt[1];
}
float avg1 = sum1 / adjustedPoints.size();
float avg2 = sum2 / adjustedPoints.size();
// Compute the new offset for the second camera to make its average match the first camera's average.
// We want to know how much and in which direction to shift the second camera's pixel values. The
// second camera's offset is what is added to the raw pixel values before gain is applied, so we need to
// subtract the needed delta divided by the gain from the current offset.
float delta = avg2 - avg1;
float newOffset2 = offset2 - (delta / newGain2);
return { newOffset2, newGain2 };
}
static void AutoUpdateColorOffsetsAndGains(void* /* unused */)
{
if (!g_pointCorrespondences) {
std::cerr << "AutoUpdateColorOffsetsAndGains(): Error: No point correspondences object available." << std::endl;
return;
}
// Get a consistent set of images to use for the adjustment.
std::vector< std::shared_ptr<ImageData> > imageSet = GetConsistentImageSet();
if (imageSet.size() != g_visibleCameras.size()) {
UnlockConsistentImageSet(imageSet);
std::cerr << "AutoUpdateColorOffsetsAndGains(): Error: Could not get consistent image set." << std::endl;
return;
}
// Update the color offsets on the second of each camera pair based on the first. Pass the appropriate
// image pair along with the image infos.
// image pair along with the image infos.
for (const auto& cameraPair : g_cameraPairs) {
std::vector<PointCorrespondences::PointPair> correspondences =
g_pointCorrespondences->CorrespondencesForCameraPair(cameraPair);
if (correspondences.empty()) {
std::cerr << "Warning: No correspondences found for camera pair: ("
<< cameraPair[0] << ", " << cameraPair[1] << "), skipping color adjustment" << std::endl;
continue;
}
// Find the indices of the entries in g_visibleCameras whose camIS fields match the two cameras in the pair.
size_t index1 = SIZE_MAX, index2 = SIZE_MAX;
for (size_t i = 0; i < g_visibleCameras.size(); i++) {
if (g_visibleCameras[i]->m_ID == cameraPair[0]) {
index1 = i;
}
if (g_visibleCameras[i]->m_ID == cameraPair[1]) {
index2 = i;
}
}
if (index1 == SIZE_MAX || index2 == SIZE_MAX) {
std::cerr << "Warning: One or both cameras not found for camera pair: ("
<< cameraPair[0] << ", " << cameraPair[1] << "), skipping color adjustment" << std::endl;
continue;
}
// Compute the offset adjustment needed.
std::array<float, 2> newOffsetGain = ComputeNewColorOffsetGain(correspondences,
imageSet[index1], imageSet[index2],
g_visibleCameras[index1], g_visibleCameras[index2]);
// Apply the offset adjustment to the second camera in the pair.
std::shared_ptr<asdp::render::CameraRenderInfo> cri = g_visibleCameras[index2];
cri->SetColorOffsetGain(newOffsetGain[0], newOffsetGain[1]);
}
// Done with the images, unlock them.
UnlockConsistentImageSet(imageSet);
}
/// @brief Callback handler to save the camera configuration to a file.
static void SaveCameraConfig(const std::string& filename, void* userdata)
{
if (g_visibleCameras.empty()) {
std::cerr << "Error: No cameras to save configuration for." << std::endl;
return;
}
if (!userdata) {
std::cerr << "Error: No user data provided for callback handler." << std::endl;
return;
}
CallbackHandlerData* data = static_cast<CallbackHandlerData*>(userdata);
// Parse the original JSON configuration file for the camera configuration directly, then replace
// the color offsets and gains for each camera with those currenttly stored because they may have been
// adjusted by the user.
json cameraConfig;
try {
std::ifstream configFile(data->cameraConfigFileName);
cameraConfig = json::parse(configFile);
} catch (const std::exception& e) {
std::cerr << "Error: Unable to read camera configuration file: " << data->cameraConfigFileName
<< ": " << e.what() << std::endl;
std::cerr << " (Cannot save configuration file)" << std::endl;
return;
}
// Iterate through the cameras and update their color offsets and gains.
for (auto& camera : cameraConfig["cameras"]) {
uint16_t id = camera["id"];
for (auto& cri : g_visibleCameras) {
if (cri->m_ID == id) {
float offset, gain;
cri->GetColorOffsetGain(offset, gain);
camera["color"]["offset"] = offset;
camera["color"]["gain"] = gain;
break; // Found the camera, no need to continue.
}
}
}
// Write the updated configuration to the specified file
try {
std::ofstream outFile(filename);
outFile << cameraConfig.dump(2); // Pretty print with 2 spaces.
outFile.close();
std::cout << "Saved camera configuration to: " << filename << std::endl;
} catch (const std::exception& e) {
std::cerr << "Error: Unable to write camera configuration file: " << filename
<< ": " << e.what() << std::endl;
}
}
/// @brief Thread to compute the depth information for the cameras and update the meshes.
/// @details The CopyDepthInfo callback handler transfers the vertex buffers from the
/// @param timer Timer to use for getting the current time for depth estimation.
/// @param depthContext DisplayTexture to use for borrowing an OpenGL context to update the meshes.
/// CameraRenderInfo inline during rendering.
static void DepthThreadFunction(std::shared_ptr<Timer> timer, std::shared_ptr<DisplayTexture> depthContext)
{
if (!depthContext->BorrowContext()) {
std::cerr << "DepthThreadFunction(): Error: Could not borrow OpenGL context." << std::endl;
return;
}
while (g_runDepthThread) {
g_timingInfo.depthComputeStartTimes.push_back(std::chrono::steady_clock::now());
// Make a snapshot of the images from all cameras at the same time and store it into
// a custom ImageQueue that has a single entry from the same time for all of them.
/// @todo
Time now;
Status status = timer->GetCoreTime(now);
if (status != OKAY) {
std::cerr << "Failed to get time: " << ErrorMessage(status) << std::endl;
return;
}
/// @todo Consider another approach to finding the time for the estimate.
try {
std::string ret = g_depthEstimator->ComputeDepthEstimate(now);
if (ret != "") {
std::cerr << "Error computing depth estimate: " << ret << std::endl;
return;
} else {
g_depthEstimator->UpdateMeshesGPU(g_visibleCameras);
}
} catch (const std::exception& e) {
std::cerr << "Exception while computing depth estimate: " << e.what() << std::endl;
return;
}
g_timingInfo.depthComputeEndTimes.push_back(std::chrono::steady_clock::now());
std::this_thread::sleep_for(std::chrono::milliseconds(1)); // Sleep a bit to avoid eating a whole CPU.
}
depthContext->ReturnContext();
}
/// @brief Callback handler to compute depth information for the cameras.
static void CopyDepthInfo(Time renderTime, void* /* unused */)
{
g_timingInfo.depthStartTimes.push_back(std::chrono::steady_clock::now());
// Update the vertex buffers for all of the visible cameras with the new depth information.
// The depth updates are computed by DepthThreadFunction, which runs in a separate thread
// and updates the vertex buffers in the CameraRenderInfo objects inline.
for (std::shared_ptr<asdp::render::CameraRenderInfo> cri : g_visibleCameras) {
g_composite->UpdateVertexBuffer(*cri);
}
g_timingInfo.depthEndTimes.push_back(std::chrono::steady_clock::now());
}
/// @brief Callback handler to turn on and off depth rendering on the visible cameras.
static void SetDepthRendering(bool depthRendering, void* /* unused */)
{
for (std::shared_ptr<asdp::render::CameraRenderInfo> cri : g_visibleCameras) {
if (depthRendering) {
// Set to clamp to white at a distance of 200 meters, to give us some resolution below that.
cri->m_depthScale = 1.0f / 200;
} else {
cri->m_depthScale = -1.0f;
}
}
std::cout << "Toggled depth rendering to: " << (depthRendering ? "on" : "off") << std::endl;
}
static std::shared_ptr<Message> WaitForMessageType(std::shared_ptr<Receiver> receiver, MessageID type, float seconds)
{
std::shared_ptr<Message> empty; ///< We return this on failure.
std::chrono::steady_clock::time_point start = std::chrono::steady_clock::now();
do {
std::shared_ptr<StreamPacket> response;
size_t offset = 0;
Status status = receiver->ReceiveStreamPacket(0, response, offset);
if ((status != OKAY) && (status != TIMEOUT)) {
return empty;
}
if (response != nullptr) {
std::shared_ptr<Message> message;
status = response->GetNextMessage(message);
if (status != OKAY) {
return empty;
}
while (message != nullptr) {
MessageID messageType;
status = message->GetType(messageType);
if (status != OKAY) {
return empty;
}
if (messageType == type) {
// Worked!
return message;
}
status = response->GetNextMessage(message);
if (status != OKAY) {
return empty;
}
}
}
} while (std::chrono::duration<double>(std::chrono::steady_clock::now() - start).count() <= seconds);
return empty;
}
/// @param [out] replayDone Set to true if we are at the end of replay, set to false otherwise.
static Status HandleStreamPacket(std::shared_ptr<StreamPacket> packet, std::shared_ptr<ClockSynchronizer> clockSync,
std::shared_ptr<PoseAdjuster> poseAdjuster, bool &replayDone, std::vector<std::shared_ptr<Display>> &displays,
std::shared_ptr<Timer> timer, Time &pausedTime)
{
// Not done replaying unless we get a message telling us that we are.
replayDone = false;
// Parse all of the messages in the stream packet, handling each of them in turn.
std::shared_ptr<Message> message;
Status status = packet->GetNextMessage(message);
if (OKAY != status) {
return status;
}
while (message != nullptr) {
MessageID messageType;
status = message->GetType(messageType);
if (OKAY != status) {
return status;
}
switch (messageType) {
case EVENT:
{
// Find the event type and handle it.
MessageEvent event(*message);
if (event.GetConstructorStatus() != OKAY) {
return event.GetConstructorStatus();
}
EventID eventType;
status = event.GetType(eventType);
if (status != OKAY) {
return status;
}
// Get the string message.
std::string messageString;
status = event.GetParam(messageString);
if (status != OKAY) {
return status;
}
switch (eventType) {
case START_OF_REPLAY:
{
// Reset the clock-sync estimates when we start, stop, or resume replay.
clockSync->ClearHistory();
}
break;
case END_OF_REPLAY:
{
// Reset the clock-sync estimates when we start, stop, or resume replay.
clockSync->ClearHistory();
}
break;
case REPLAY_PAUSED:
{
// Store the time that we're paused at so that we can reset our clock-sync estimates
// when we resume.
status = message->GetTime(pausedTime);
if (status != OKAY) {
return status;
}
// Tell all of our Displays that we're paused.
for (auto &display : displays) {
display->SetNowPlaying(false);
}
}
break;
case REPLAY_RESUMED:
{
// Reset the clock-sync estimates when we start, stop, or resume replay.
clockSync->ClearHistory();
// Add an entry to the clock-sync estimates based on the time we were paused,
// making the current time match it. Then reset the history again so that this
// phantom entry doesn't affect the estimates. We needed to reset the history
// before doing this so that our single entry causes the shift that we want.
if (!clockSync->AddDataPoint(pausedTime, std::chrono::steady_clock::now())) {
return UNEXPECTED_INTERNAL_STATE;
}
clockSync->ClearHistory();
// Tell all of our Displays that we're no longer paused.
for (auto& display : displays) {
display->SetNowPlaying(true);
}
}
break;
case CLOCK_SYNC:
{
// Adjust the timer offset based on clock-sync messages. The first message (or the first one
// after replay resumes, or the first one after replay stops), sets the estimated offset based
// on that single number and the relative rate to 1.0. Later ones adjust based on an average of
// the previous ones as described in the render implementation document.
Time messageTime;
status = message->GetTime(messageTime);
if (status != OKAY) {
return status;
}
clockSync->AddDataPoint(messageTime, std::chrono::steady_clock::now());
g_lastCLOCK_SYNC = messageTime;
}
break;
case INVALID_OPERATION:
{
// If we get an invalid operation message, say so
std::cerr << "Invalid operation message received from server: " << messageString << std::endl;
}
break;
case INTERNAL_ERROR:
{
// If we get an internal error message, say so
std::cerr << "Internal error message received from server: " << messageString << std::endl;
}
break;
case UNRECOGNIZED_OPCODE:
{
// If we get an unrecognized opcode message, say so
std::cerr << "Unrecognized opcode message received from server: " << messageString << std::endl;
}
break;
default:
break;
}
}
break;
case STATE:
{
// Parse the state message and keep track of anything we need to.
MessageState state(*message);
if (state.GetConstructorStatus() != OKAY) {
return state.GetConstructorStatus();
}
uint8_t replaying;
status = state.GetReplaying(replaying);
if (status != OKAY) {
return status;
}
//std::cout << "XXX Replaying = " << (replaying ? "true" : "false") << std::endl;
// If we're replaying and we're at the end of replay, indicate this.
if (replaying) {
uint8_t endOfReplay;
status = state.GetReplayAtEnd(endOfReplay);
if (status != OKAY) {
return status;
}
if (endOfReplay) {
replayDone = true;
}
}
}
break;
case POSE:
{
// Parse the pose message and add the pose to the adjuster.
MessagePose pose(*message);
if (pose.GetConstructorStatus() != OKAY) {
return pose.GetConstructorStatus();
}
poseAdjuster->AddPose(pose);
}
break;
default:
// Ignore other message types.
break;
}
status = packet->GetNextMessage(message);
if (OKAY != status) {
return status;
}
}
return OKAY;
}
/// @brief Structure to hold display information
struct DisplayInfo
{
ToneMap toneMap = ToneMap(); ///< The tone map to use.
bool useOpenXR = false; ///< Use OpenXR for rendering? If so, overrides all of the following.
std::string XSightNIC = ""; ///< NIC to listen to XSight on for rendering. If not empty, overrides all of the following.
int XSightDisplay = 1; ///< The display to use for XSight rendering.
std::string XSight2NIC = ""; ///< NIC to listen to XSight2 on for rendering. If not empty, overrides all of the following.
int XSight2Display = 1; ///< The display to use for XSight2 rendering.
int width = 1280; ///< The width of the display.
int height = 1024; ///< The height of the display.
float hFOV = 40.0f; ///< The horizontal field of view in degrees.
std::string joystick = ""; ///< The joystick to use for input.
float fps = 60.0f; ///< The frames per second to run at.
bool fullScreen = false; ///< Run in full screen mode.
int fullScreenDisplay = 0; ///< The display to run in full screen mode on.
std::array<float, 3> viewpointOffset = { 0.0f, 0.0f, 0.0f }; ///< The offset to apply to the viewpoint for this display, in meters.
//======================================
// Added by Sang Yoon to add a flag for enabling the cylindrical projection.
bool enableCP = false; ///< The flag to enable the cylindrical projection
//======================================
//======================================
// Added by Sang Yoon to indicate if the window associated with the display is overview window, detailed view windowe, or neither.
// Where the number of displays is greater than 1, the window that has the widest horizontal FOV is considered as an overview window,
// and the window that has the narrowest hFOV is considered as a detailed view window.
bool overview = false;
bool detailed_view = false;
//======================================
};
static std::string TimeIntervalToStringMilliseconds(std::chrono::duration<float> interval)
{
std::ostringstream oss;
oss << std::fixed << std::setprecision(9) << interval.count() * 1000;
return oss.str();
}
static std::chrono::steady_clock::time_point LargestTimeLessThan(std::chrono::steady_clock::time_point time,
const std::vector<std::chrono::steady_clock::time_point>& times)
{
std::chrono::steady_clock::time_point largest = std::chrono::steady_clock::time_point::min();
for (auto &t : times) {
if (t < time) {
largest = std::max(largest, t);
}
}