-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDepthEstimator.cu
More file actions
2583 lines (2268 loc) · 119 KB
/
Copy pathDepthEstimator.cu
File metadata and controls
2583 lines (2268 loc) · 119 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-2026: Arizona Board of Regents on Behalf of the University of Arizona
*/
#include <iostream>
#include <chrono>
#include <memory>
#include <map>
#include <random>
#include <cstddef>
#include <WindowCreation.h>
#include <ToneMap.h>
#include <DepthEstimator.h>
#include <Composite.h>
#include <cuda.h>
#include <cuda_runtime.h>
#include <cuda_gl_interop.h>
using namespace asdp;
using namespace asdp::render;
//==================================================================================================
// Helper classes for dealing with vectors and Quaternions because we can't use GLM in CUDA kernels.
// They are available on both host and device.
struct Vec3 {
float vals[3];
__host__ __device__ Vec3() : vals{0, 0, 0} {}
__host__ __device__ Vec3(float x, float y, float z) : vals{x, y, z} {}
__host__ __device__ Vec3(glm::vec3 v) : vals{ v.x, v.y, v.z } {}
__host__ __device__ Vec3(glm::dvec3 v) : vals{ (float)v.x, (float)v.y, (float)v.z } {}
// Index operator.
__host__ __device__ float& operator[](size_t index) {
return vals[index];
}
// Arithmetic operations.
__host__ __device__ Vec3 operator-(const Vec3& other) const {
return Vec3(vals[0] - other.vals[0], vals[1] - other.vals[1], vals[2] - other.vals[2]);
}
__host__ __device__ Vec3 operator+(const Vec3& other) const {
return Vec3(vals[0] + other.vals[0], vals[1] + other.vals[1], vals[2] + other.vals[2]);
}
__host__ __device__ Vec3 operator*(float scalar) const {
return Vec3(vals[0] * scalar, vals[1] * scalar, vals[2] * scalar);
}
__host__ __device__ bool operator==(const Vec3 other) const {
return (vals[0] == other.vals[0]) && (vals[1] == other.vals[1]) && (vals[2] == other.vals[2]);
}
__host__ __device__ bool operator!=(const Vec3 other) const {
return !((*this) == other);
}
// Normalization.
__host__ __device__ float Length() const {
return sqrt(vals[0] * vals[0] + vals[1] * vals[1] + vals[2] * vals[2]);
}
__host__ __device__ Vec3 Normalize() const {
float length = Length();
if (length > 0.0f) {
return Vec3(vals[0] / length, vals[1] / length, vals[2] / length);
} else {
return Vec3(0, 0, 0);
}
}
// Dot product.
__host__ __device__ float Dot(const Vec3& other) const {
return vals[0] * other.vals[0] + vals[1] * other.vals[1] + vals[2] * other.vals[2];
}
};
struct Quat {
float vals[4];
__host__ __device__ Quat() : vals{0, 0, 0, 1} {}
__host__ __device__ Quat(float x, float y, float z, float w) : vals{x, y, z, w} {}
__host__ __device__ Quat(glm::quat q) : vals{ q.x, q.y, q.z, q.w } {}
__host__ __device__ Quat(glm::dquat q) : vals{ (float)q.x, (float)q.y, (float)q.z, (float)q.w } {}
// Index operator.
__host__ __device__ float& operator[](size_t index) {
return vals[index];
}
// Quaternion multiplication of a Vec3 to rotate it.
__host__ __device__ Vec3 operator*(const Vec3& v) const {
// q.xyz
Vec3 qv(vals[0], vals[1], vals[2]);
// t = 2 * cross(qv, v)
Vec3 t = Vec3(
qv[1] * v.vals[2] - qv[2] * v.vals[1],
qv[2] * v.vals[0] - qv[0] * v.vals[2],
qv[0] * v.vals[1] - qv[1] * v.vals[0]
) * 2.0f;
// v' = v + q.w * t + cross(qv, t)
Vec3 v_prime = v + (t * vals[3]);
Vec3 cross_q_t = Vec3(
qv[1] * t.vals[2] - qv[2] * t.vals[1],
qv[2] * t.vals[0] - qv[0] * t.vals[2],
qv[0] * t.vals[1] - qv[1] * t.vals[0]
);
return v_prime + cross_q_t;
}
};
//==================================================================================================
/// Maximum block size for the CUDA kernel, which matches the maximum number of samples in X or Y.
/// This is the size of the image that each block of threads will process. This includes all of
/// the passes for the block, so it is the number of pixels in X and Y divided by the number of
/// regions in X and Y.
static const size_t MAX_BLOCK_SIZE = 100;
/// @brief CUDA kernel to compute the differences between two surfaces (OpenGL textures).
/// @details The kernel computes the mean squared difference between the corresponding pixels in two
/// RGBA or BGRA textures. The kernel is designed to be run in blocks of threads, with each block
/// processing a region of the image. Because the number of pixels in a block is larger than the
/// maximum number of threads in a block, each thread may handle pixels from multiple rows. To minimize
/// calculations in the kernel, the number of iterations is a parameter to the kernel, as is the number
/// of rows in an iteration and the number of rows in each block. The number of columns in the block is
/// always the same as the X block dimension. The kernel uses shared memory to store the results for
/// each thread in the block and then computes the sum and count of the valid values in each row in a
/// subset of the threads. It the sums the sums and counts and computes the final average using a
/// single thread.
/// @param surface1, surface2 The surfaces to compare. They are RGBA or BGRA textures.
/// @param out The per-region array of output values to write.
/// @param iterations The number of iterations to run.
/// @param rowsPerIteration The number of rows to process in each iteration.
/// @param rowsPerBlock The number of rows to process in each block.
__global__ void CompareSurfacesKernel(cudaSurfaceObject_t surface1, cudaSurfaceObject_t surface2, float* out,
unsigned iterations, unsigned rowsPerIteration, unsigned rowsPerBlock)
{
/// Block of memory to store the within-block results.
__shared__ float sharedMem[MAX_BLOCK_SIZE][MAX_BLOCK_SIZE];
__shared__ float rowSums[MAX_BLOCK_SIZE];
__shared__ int rowCounts[MAX_BLOCK_SIZE];
// Global coordinates in the images.
// There are as many Y threads as there are rows in an iteration, with potentially many iterations
// per block. The number of rows per block is how much should be skipped in Y rather than the
// block to cause each block of threads to handle that portion of the image. We offset each thread
// within the first iteration here to compute a base, which is then bumped per iteration. There is
// enough room in shared memory for the entire block (all iterations).
unsigned x = blockIdx.x * blockDim.x + threadIdx.x;
unsigned yBase = blockIdx.y * rowsPerBlock + threadIdx.y;
unsigned xLocal = threadIdx.x;
for (unsigned iter = 0; iter < iterations; iter++) {
unsigned yLocal = threadIdx.y + iter * rowsPerIteration;
unsigned y = yBase + iter * rowsPerIteration;
// The block size matches the number of threads in X, and the block size evenly divides the image,
// so we don't need to check bounds on that axis.
if (yLocal < rowsPerBlock) {
// Read the data from both surfaces. The x coordinate is in bytes, so we need to multiply by the
// size of the data type.
// The image size is a multiple of the block size, so we don't need to check for out-of-bounds.
uchar4 val1, val2;
surf2Dread(&val1, surface1, x * sizeof(val1), y);
surf2Dread(&val2, surface2, x * sizeof(val2), y);
// If the first and third colors are not the same in either of the values, then the region is outside
// of the projected area (the pixel is blue), so we record -1 as the value. Otherwise, we record the
// squared difference between the first color in each value. We have enough entries for all threads
// in the block, we use the thread index to determine where to write.
if ((val1.x != val1.z) || (val2.x != val2.z)) {
sharedMem[yLocal][xLocal] = -1.0f;
} else {
float diff = val1.x - val2.x;
sharedMem[yLocal][xLocal] = diff * diff;
}
}
}
// Wait until all threads in the block have completed and then have the first thread in each
// row compute the sum and count of the valid values in the row.
__syncthreads();
for (unsigned iter = 0; iter < iterations; iter++) {
unsigned yLocal = threadIdx.y + iter * rowsPerIteration;
if (yLocal < rowsPerBlock) {
// @todo We can get better utilization if we have threads in different columns handle
// the different rows rather than looping over iterations.
if (threadIdx.x == 0) {
rowSums[yLocal] = 0.0f;
rowCounts[yLocal] = 0;
for (size_t i = 0; i < blockDim.x; i++) {
float val = sharedMem[yLocal][i];
if (val >= 0.0f) {
rowSums[yLocal] += val;
rowCounts[yLocal]++;
}
}
}
}
}
// Wait until all threads in the block have completed and then have one thread sum the
// sum and counts and compute the final average.
__syncthreads();
if (threadIdx.x == 0 && threadIdx.y == 0) {
float sum = 0.0f;
int count = 0;
// Sum over the entire block's worth of rows, not just the first iteration's
for (size_t i = 0; i < rowsPerBlock; i++) {
sum += rowSums[i];
count += rowCounts[i];
}
// Avoid division by zero, return 0 in the case of no valid values.
if (count == 0) { count = 1; }
out[blockIdx.x + blockIdx.y * gridDim.x] = sum/count;
}
}
static std::shared_ptr<ImageData> MakeBlankImage(int width, int height)
{
std::vector<uint16_t> image(width * height, 32767);
std::shared_ptr<ImageData> imageData = std::make_shared<ImageData>();
unsigned int texture;
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);
// Set the texture wrapping parameters
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
// Set texture filtering parameters
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
// Load image into the texture
glTexStorage2D(GL_TEXTURE_2D, 1, GL_R16, width, height);
glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width, height, GL_RED, GL_UNSIGNED_SHORT, image.data());
glBindTexture(GL_TEXTURE_2D, 0);
imageData->texture = texture;
return imageData;
}
/// @brief Encapsulates the multiple depths for each camera pair.
/// @details Generate two sets of CompositeCameras covering all depths for each pair of cameras,
/// one set for the left camera and one for the right camera.
class CameraPairInfo {
public:
CameraPairInfo() = delete;
CameraPairInfo(ToneMap const &toneMap, std::shared_ptr<CameraRenderInfo> camera1, std::shared_ptr<CameraRenderInfo> camera2,
std::shared_ptr<asdp::render::RangeEstimator> rangeEstimator,
glm::dvec3 position, glm::dquat orientation,
std::array<float, 2> fovsDeg, std::array<unsigned, 2> pixelCounts,
std::shared_ptr<PoseAdjuster> poseAdjuster, Time cameraFrameInterval,
std::vector<float> depths, float defaultDepth)
: m_cameras({camera1, camera2})
, m_position(position)
, m_orientation(orientation)
, m_fovsDeg(fovsDeg)
, m_pixelCounts(pixelCounts)
, m_poseAdjuster(poseAdjuster)
{
// Construct the tone map to use.
m_toneMapTexture = toneMap.GenerateTexture();
// Create the composite cameras for each depth, adjusting the camera render info to suit.
for (float depth : depths) {
PerDepth depthInfo;
depthInfo.m_depth = depth;
// We make a copy of each camera and then adjust the copy to the specific depth it is to use.
// Also construct a new image queue for each; we will push a consistent pair of images from
// the two cameras into the queues for each camera and clear out any old images in the queue.
// We need to put a single image into each queue so that there will be something to grab
// until we put an actual image in place.
std::shared_ptr<CameraRenderInfo> depth1(new CameraRenderInfo(*camera1));
depth1->m_imageQueue = std::make_shared<asdp::render::ImageQueue>();
depthInfo.m_imageQueues[0] = depth1->m_imageQueue;
depth1->m_imageQueue->InsertImage(MakeBlankImage(depth1->m_resolutionPixels[0], depth1->m_resolutionPixels[1]));
depth1->ComputePlanarCameraMeshInfo(100, 100, depth);
std::vector< std::shared_ptr<CameraRenderInfo> > composites1;
composites1.push_back(depth1);
depthInfo.m_composites[0] = std::make_shared<CompositeCameras>(composites1, m_toneMapTexture,
m_poseAdjuster, cameraFrameInterval, 0, Time(), nullptr, rangeEstimator);
std::shared_ptr<CameraRenderInfo> depth2(new CameraRenderInfo(*camera2));
depth2->m_imageQueue = std::make_shared<asdp::render::ImageQueue>();
depthInfo.m_imageQueues[1] = depth2->m_imageQueue;
depth2->m_imageQueue->InsertImage(MakeBlankImage(depth2->m_resolutionPixels[0], depth2->m_resolutionPixels[1]));
depth2->ComputePlanarCameraMeshInfo(100, 100, depth);
std::vector< std::shared_ptr<CameraRenderInfo> > composites2;
composites2.push_back(depth2);
depthInfo.m_composites[1] = std::make_shared<CompositeCameras>(composites2, m_toneMapTexture,
m_poseAdjuster, cameraFrameInterval, 0, Time(), nullptr, rangeEstimator);
// Generate a pair of frame buffers for the two cameras, with an associated color and depth
// buffer for each.
glGenFramebuffers(2, depthInfo.m_frameBuffers.data());
glGenTextures(2, depthInfo.m_colorBuffers.data());
for (size_t b = 0; b < depthInfo.m_colorBuffers.size(); b++) {
glBindTexture(GL_TEXTURE_2D, depthInfo.m_colorBuffers[b]);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, pixelCounts[0], pixelCounts[1], 0,
GL_RGBA, GL_UNSIGNED_BYTE, nullptr);
glBindTexture(GL_TEXTURE_2D, 0);
}
glGenTextures(2, depthInfo.m_depthBuffers.data());
for (size_t b = 0; b < depthInfo.m_depthBuffers.size(); b++) {
glBindTexture(GL_TEXTURE_2D, depthInfo.m_depthBuffers[b]);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT32, pixelCounts[0], pixelCounts[1], 0, GL_DEPTH_COMPONENT, GL_FLOAT, nullptr);
glBindTexture(GL_TEXTURE_2D, 0);
}
// Map the CUDA graphics resources for the color buffers.
for (size_t b = 0; b < depthInfo.m_colorBuffers.size(); b++) {
cudaError_t res = cudaGraphicsGLRegisterImage(&depthInfo.m_cudaColorBuffers[b], depthInfo.m_colorBuffers[b],
GL_TEXTURE_2D, cudaGraphicsRegisterFlagsSurfaceLoadStore);
if (res != cudaSuccess) {
m_constructorStatus = "Failed to register image: " + std::string(cudaGetErrorString(res));
return;
}
}
// Create the CUDA streams.
cudaStream_t* streamPtr = new cudaStream_t;
cudaError_t res = cudaStreamCreate(streamPtr);
if (res != cudaSuccess) {
m_constructorStatus = "Failed to create stream: " + std::string(cudaGetErrorString(res));
return;
}
depthInfo.m_stream = streamPtr;
// Zero the GPU and memory for the region buffer; it will be allocated the first time it is needed.
depthInfo.m_GPURegionBuffer = nullptr;
m_perDepths.push_back(depthInfo);
}
// Fill in the default depth for all regions.
m_depths.resize(pixelCounts[0] * pixelCounts[1], defaultDepth);
}
~CameraPairInfo() {
// Delete the tone map texture.
glDeleteTextures(1, &m_toneMapTexture);
// Delete the frame buffers, color buffers, and depth buffers.
// Unmap the CUDA graphics resources for the color buffers.
// Delete the CUDA streams.
// Free the GPU memory for the depth buffers.
for (PerDepth &di : m_perDepths) {
glDeleteFramebuffers(2, di.m_frameBuffers.data());
for (size_t b = 0; b < di.m_cudaColorBuffers.size(); b++) {
cudaGraphicsUnregisterResource(di.m_cudaColorBuffers[b]);
}
glDeleteTextures(2, di.m_colorBuffers.data());
glDeleteTextures(2, di.m_depthBuffers.data());
cudaFree(di.m_GPURegionBuffer);
cudaStreamDestroy(*(di.m_stream));
}
}
std::array<std::shared_ptr<CameraRenderInfo>,2 > m_cameras;
std::shared_ptr<PoseAdjuster> m_poseAdjuster;
glm::dvec3 m_position;
glm::dquat m_orientation;
std::array<float, 2> m_fovsDeg;
std::array<unsigned, 2> m_pixelCounts;
GLuint m_toneMapTexture;
class PerDepth {
public:
float m_depth = 0.0f;
std::vector<float> m_CPURegionBuffer;
float* m_GPURegionBuffer;
cudaStream_t* m_stream = nullptr;
/// @todo Consider pulling these out into yet another structure, making an array of 2 of them.
std::array< std::shared_ptr<CompositeCameras>, 2> m_composites = {};
/// Per-camera custom image queue for each depth. This is a bit of a complicated scheme.
/// We determine consistent-timed frames from the two real cameras in each pair and then
/// copy these images into the custom ImageQueues for all depths associated with that pair
/// so that they will always be generating depths from consistent values across all depths.
std::array< std::shared_ptr<ImageQueue>, 2> m_imageQueues = {};
std::array<GLuint, 2> m_frameBuffers = {};
std::array<GLuint, 2> m_colorBuffers = {};
std::array<GLuint, 2> m_depthBuffers = {};
std::array<cudaGraphicsResource*, 2> m_cudaColorBuffers = {};
};
std::vector<PerDepth> m_perDepths;
/// Computed estimated depth at every region location.
std::vector<float> m_depths;
std::string m_constructorStatus;
};
//==================================================================================================
// Object that forms a packed structure that contains the relevant entries from all available
// CameraPairInfo objects in a DepthEstimatorImpl for use in CUDA kernels.
struct CameraPairsKernelData {
CameraPairsKernelData() = delete;
/// @brief Constructor for the CPU-side code allocates memory and fills in the data.
CameraPairsKernelData(std::vector< std::shared_ptr<CameraPairInfo> > const& cameraPairs) : m_cameraPairs(cameraPairs)
{
totalSizeFloats = 1;
// The fixed-size camera pair info for each pair
totalSizeFloats += cameraPairs.size() * CameraPairBaseInfoSize;
// The depth information for each pair
for (auto const& pair : cameraPairs) {
totalSizeFloats += pair->m_depths.size();
}
// Allocate the pinned CPU data and the GPU data
if (cudaMallocHost(&data, totalSizeFloats * sizeof(float)) != cudaSuccess) {
throw std::runtime_error("Failed to allocate pinned CameraPairsKernelData");
}
if (cudaMalloc(&kData, totalSizeFloats * sizeof(float)) != cudaSuccess) {
throw std::runtime_error("Failed to allocate GPU CameraPairsKernelData");
}
}
void CopyDataToGPU(cudaStream_t stream = 0)
{
// Fill in the data on the pinned memory
numCameraPairsCPU() = static_cast<uint32_t>(m_cameraPairs.size());
// Fixed camera size data
for (size_t i = 0; i < m_cameraPairs.size(); i++) {
auto const& pair = m_cameraPairs[i];
// Base info
pairPositionsCPU(i) = Vec3(static_cast<float>(pair->m_position.x),
static_cast<float>(pair->m_position.y),
static_cast<float>(pair->m_position.z));
pairOrientationsCPU(i) = Quat(pair->m_orientation);
pairFOVsCPU(i)[0] = pair->m_fovsDeg[0];
pairFOVsCPU(i)[1] = pair->m_fovsDeg[1];
pairPixelCountsCPU(i)[0] = static_cast<uint32_t>(pair->m_pixelCounts[0]);
pairPixelCountsCPU(i)[1] = static_cast<uint32_t>(pair->m_pixelCounts[1]);
}
// Camera pair depth information
for (size_t i = 0; i < m_cameraPairs.size(); i++) {
auto const& pair = m_cameraPairs[i];
float* depths = pairDepthsCPU(i);
for (size_t j = 0; j < pair->m_depths.size(); j++) {
depths[j] = pair->m_depths[j];
}
}
// Initiate a copy of the data to the GPU using the provided stream.
cudaError_t res = cudaMemcpyAsync(kData, data, totalSizeFloats * sizeof(float), cudaMemcpyHostToDevice, stream);
if (res != cudaSuccess) {
throw std::runtime_error("Failed to copy CameraPairsKernelData to GPU: " + std::string(cudaGetErrorString(res)));
}
}
/// @brief Destructor frees the allocated memory.
~CameraPairsKernelData()
{
cudaFree(data);
data = nullptr;
cudaFree(kData);
kData = nullptr;
}
/// This is a horrible hack to pack all of the data into a single vector of floats and then
/// provide accessors to the individual entries, some of which are not floats.
float* data = nullptr;
/// This is an even more horrible hack that defines different accessors for the info on the CPU and
/// kernel sides based on the correct pointer. This is the pointer to be used on the GPU kernel.
float* kData = nullptr;
/// The total size in floats of the data.
size_t totalSizeFloats = 0;
/// The size of the base info for each camera pair.
static const size_t CameraPairBaseInfoSize = 3 + 4 + 2 + 2; // position(3) + orientation(4) + fovs(2) + pixelCounts(2)
/// The first thing packed is the number of camera pairs.
static __host__ __device__ uint32_t& numCameraPairs(float *d) { return *reinterpret_cast<unsigned int*>(&d[0]); }
__host__ uint32_t& numCameraPairsCPU() const { return numCameraPairs(data); }
__device__ uint32_t& numCameraPairsGPU() const { return numCameraPairs(kData); }
/// The second batch of things packed is the base info for each camera pair, with all data for each together.
static __host__ __device__ Vec3& pairPositions(float* d, size_t i) {
return *reinterpret_cast<Vec3*>(&d[1 + i * CameraPairBaseInfoSize]);
};
__host__ Vec3& pairPositionsCPU(size_t i) const { return pairPositions(data, i); };
__device__ Vec3& pairPositionsGPU(size_t i) const { return pairPositions(kData, i); };
static __host__ __device__ Quat& pairOrientations(float* d, size_t i) {
return *reinterpret_cast<Quat*>(&d[1 + i * CameraPairBaseInfoSize + 3]);
};
__host__ Quat& pairOrientationsCPU(size_t i) const { return pairOrientations(data, i); };
__device__ Quat& pairOrientationsGPU(size_t i) const { return pairOrientations(kData, i); };
static __host__ __device__ float* pairFOVs(float* d, size_t i) {
return &d[1 + i * CameraPairBaseInfoSize + 7];
};
__host__ float* pairFOVsCPU(size_t i) const { return pairFOVs(data, i); };
__device__ float* pairFOVsGPU(size_t i) const { return pairFOVs(kData, i); };
static __host__ __device__ uint32_t* pairPixelCounts(float* d, size_t i) {
return reinterpret_cast<uint32_t*>(&d[1 + i * CameraPairBaseInfoSize + 9]);
};
__host__ uint32_t* pairPixelCountsCPU(size_t i) const { return pairPixelCounts(data, i); };
__device__ uint32_t* pairPixelCountsGPU(size_t i) const { return pairPixelCounts(kData, i); };
/// The next batch of things packed are the depth values per pair.
static __host__ __device__ float* pairDepths(float* d, size_t i) {
size_t depthIndex = 1 + numCameraPairs(d) * CameraPairBaseInfoSize;
for (size_t p = 0; p < i; p++) {
uint32_t* pixCounts = pairPixelCounts(d, p);
depthIndex += pixCounts[0] * pixCounts[1];
}
return &d[depthIndex];
};
__host__ float* pairDepthsCPU(size_t i) const { return pairDepths(data, i); };
__device__ float* pairDepthsGPU(size_t i) const { return pairDepths(kData, i); };
protected:
/// Stores the camera pairs for when we need to refer back to them.
std::vector< std::shared_ptr<CameraPairInfo> > m_cameraPairs;
};
//==================================================================================================
// Input data structure to compact and copy the normalizedOffsets for a CameraRenderInfo.
struct CameraOffsetInfoKernelData {
CameraOffsetInfoKernelData() = delete;
/// @brief Constructor for the CPU-side code allocates memory and fills in the data.
/// @details The data in the data pointers is undefined until after CopyDataToGPU is called.
/// @param cameraRenderInfo The camera render info object to manage depth data for.
CameraOffsetInfoKernelData(std::shared_ptr<CameraRenderInfo> cameraRenderInfo) : cri(cameraRenderInfo) {
// Allocate the data, pinned memory on the host and GPU memory for the device.
if (cudaMallocHost(&data, cri->m_mesh.vertexInfo.size() * 3 * sizeof(float)) != cudaSuccess) {
throw std::runtime_error("Failed to allocate CameraOffsetInfoKernelData");
}
if (cudaMalloc(&kData, cri->m_mesh.vertexInfo.size() * 3 * sizeof(float)) != cudaSuccess) {
throw std::runtime_error("Failed to allocate GPU CameraOffsetInfoKernelData");
}
}
/// @brief Start the copy of the data from the pinned CPU buffer to the GPU memory on the specified stream.
/// @details This initiates an asynchronous copy of the data from the CPU to the GPU memory on the
/// specified CUDA stream.
/// @param stream The CUDA stream to use for the copy.
void CopyDataToGPU(cudaStream_t stream) {
// Copy the normalized offsets into the pinned data buffer.
for (size_t j = 0; j < cri->m_mesh.vertexInfo.size(); j++) {
data[j] = Vec3(cri->m_mesh.vertexInfo[j].normalizedOffset);
}
// Initiate a copy of the data from the GPU using the provided stream.
cudaError_t res = cudaMemcpyAsync(kData, data, cri->m_mesh.vertexInfo.size() * sizeof(Vec3), cudaMemcpyHostToDevice, stream);
if (res != cudaSuccess) {
throw std::runtime_error("Failed to copy CameraOffsetInfoKernelData to GPU: " + std::string(cudaGetErrorString(res)));
}
}
/// @brief Destructor frees the allocated memory.
~CameraOffsetInfoKernelData() {
cudaFree(data);
data = nullptr;
cudaFree(kData);
kData = nullptr;
}
/// Stored camera render info used to put depths back.
std::shared_ptr<CameraRenderInfo> cri;
/// This is a horrible hack to pack all of the data into a single vector of floats and then
/// provide accessors to the individual entries, some of which are not floats.
Vec3* data = nullptr;
/// This is an even more horrible hack that defines different accessors for the info on the CPU and
/// kernel sides based on the correct pointer. This is the pointer to be used on the GPU kernel.
/// It starts out undefined and until CopyDataToGPU is called.
Vec3* kData = nullptr;
};
//==================================================================================================
// Output data structure to compact and re-fill the depth estimates for a CameraRenderInfo.
struct CameraDepthInfoKernelData {
CameraDepthInfoKernelData() = delete;
/// @brief Constructor for the CPU-side code allocates memory and fills in the data.
/// @details The data in the pinned-memory data pointer is undefined until after a copy from the GPU.
/// @param cameraRenderInfo The camera render info object to manage depth data for.
CameraDepthInfoKernelData(std::shared_ptr<CameraRenderInfo> cameraRenderInfo) : cri(cameraRenderInfo) {
// Allocate the data, pinned memory on the host and GPU memory for the device.
if (cudaMallocHost(&data, cri->m_mesh.vertexInfo.size() * sizeof(float)) != cudaSuccess) {
throw std::runtime_error("Failed to allocate CameraDepthInfoKernelData");
}
if (cudaMalloc(&kData, cri->m_mesh.vertexInfo.size() * sizeof(float)) != cudaSuccess) {
throw std::runtime_error("Failed to allocate GPU CameraDepthInfoKernelData");
}
}
/// @brief Start the copy of the data from the GPU back to the pinned CPU memory on the specified stream.
/// @details This initiates an asynchronous copy of the data from the GPU to the CPU pinned memory on the
/// specified CUDA stream.
/// @param stream The CUDA stream to use for the copy.
void CopyDataFromGPU(cudaStream_t stream) {
// Initiate a copy of the data from the GPU using the provided stream.
cudaError_t res = cudaMemcpyAsync(data, kData, cri->m_mesh.vertexInfo.size() * sizeof(float), cudaMemcpyDeviceToHost, stream);
if (res != cudaSuccess) {
throw std::runtime_error("Failed to copy CameraDepthInfoKernelData from GPU: " + std::string(cudaGetErrorString(res)));
}
}
/// @brief Fill the depths back into the CameraRenderInfo objects from the data in this structure.
/// @details This function waits for the specified stream to complete and then fills the depths
/// back into the CameraRenderInfo objects. The CopyDataFromGPU() method must have been called previously
/// to initiate the copy of the data from the GPU.
/// @param stream The CUDA stream to synchronize before filling depths.
void FillDepthsBackToCameraRenderInfos(cudaStream_t stream) {
cudaError_t ret = cudaStreamSynchronize(stream);
// Check for errors.
if (ret != cudaSuccess) {
throw std::runtime_error("Failed to synchronize stream in FillDepthsBackToCameraRenderInfos: " + std::string(cudaGetErrorString(ret)));
}
for (size_t j = 0; j < cri->m_mesh.vertexInfo.size(); j++) {
cri->m_mesh.vertexInfo[j].depth = data[j];
}
}
/// @brief Destructor frees the allocated memory.
~CameraDepthInfoKernelData() {
cudaFree(data);
data = nullptr;
cudaFree(kData);
kData = nullptr;
}
/// Stored camera render info used to put depths back.
std::shared_ptr<CameraRenderInfo> cri;
/// This is a horrible hack to pack all of the data into a single vector of floats and then
/// provide accessors to the individual entries, some of which are not floats.
float* data = nullptr;
/// This is an even more horrible hack that defines different accessors for the info on the CPU and
/// kernel sides based on the correct pointer. This is the pointer to be used on the GPU kernel.
/// It starts out undefined and should be filled in before CopyDataFromGPU() is called.
float* kData = nullptr;
};
//==================================================================================================
/// Provides implementation details for the DepthEstimator class
class DepthEstimator::DepthEstimatorImpl {
public:
friend class DepthEstimator;
DepthEstimatorImpl() = delete;
DepthEstimatorImpl(DepthEstimator *parent,
std::vector< std::array<std::shared_ptr<CameraRenderInfo>, 2> > pairs,
std::shared_ptr<asdp::render::RangeEstimator> rangeEstimator,
std::shared_ptr<PoseAdjuster> poseAdjuster,
Time cameraFrameInterval,
unsigned nx, unsigned ny,
std::vector<float> depths,
float fitnessThreshold)
: m_parent(parent)
, m_nx(nx)
, m_ny(ny)
, m_fitnessThreshold(fitnessThreshold)
{
// Find the default depth.
if (depths.size() == 0) {
// Error -- no default depth
m_defaultDepth = -1.0f;
} else {
// Use the furthest depth as the default.
m_defaultDepth = depths.back();
}
// Generate CameraPairInfo (two sets of CompositeCameras covering all depths) for each pair of cameras,
// one set for the left camera and one for the right camera. The two sets for each depth will be rendered
// separately into a pair of frame buffers with the same (average of the two cameras) view frustum
// and then compared to estimate the depth.
// NOTE: Tonemap must be monochrome because the test code calls all colored pixels background.
// The default black-to-white one works.
ToneMap toneMap;
for (unsigned i = 0; i < pairs.size(); i++) {
// For each pair, create a viewpoint that is halfway between
// the two cameras with an orientation that is the average of the two.
// We store the rotation as a quaternion and convert the Euler angles
// to quaternions to average them.
glm::dvec3 position;
std::array<double, 3> const& p1 = pairs[i][0]->m_positionMeters;
std::array<double, 3> const& p2 = pairs[i][1]->m_positionMeters;
position = 0.5 * (glm::dvec3(p1[0], p1[1], p1[2]) + glm::dvec3(p2[0], p2[1], p2[2]));
glm::quat orientation;
glm::quat rotx = glm::angleAxis(glm::radians(pairs[i][0]->m_orientationDegrees[0]), glm::dvec3(1, 0, 0));
glm::quat roty = glm::angleAxis(glm::radians(pairs[i][0]->m_orientationDegrees[1]), glm::dvec3(0, 1, 0));
glm::quat rotz = glm::angleAxis(glm::radians(pairs[i][0]->m_orientationDegrees[2]), glm::dvec3(0, 0, 1));
glm::quat rot1 = rotx * roty * rotz;
rotx = glm::angleAxis(glm::radians(pairs[i][1]->m_orientationDegrees[0]), glm::dvec3(1, 0, 0));
roty = glm::angleAxis(glm::radians(pairs[i][1]->m_orientationDegrees[1]), glm::dvec3(0, 1, 0));
rotz = glm::angleAxis(glm::radians(pairs[i][1]->m_orientationDegrees[2]), glm::dvec3(0, 0, 1));
glm::quat rot2 = rotx * roty * rotz;
orientation = glm::slerp(rot1, rot2, 0.5f);
// Determine the FOVs of the frame buffer that will be used to render the manifolds.
// It should cover the range of the manifolds, including their distortion. Then determine the
// pixel count, which should be an even multiple of the number of samples in each dimension
// and its ratio should be similar to the aspect ratio of the frame buffer and it should have
// at least as many pixels as the camera images in each dimension. Start by determining the
// distorted locations of the points at the left, right, top, and bottom of the frustum at
// Z = -1 and computing its fields of view by taking the minimum of left and right and minimum
// of top and bottom.
std::array<float, 2> fovsDeg;
double depthForFOV = 1.0;
double minHFOV = 1e10, minVFOV = 1e10;
double maxXRatio = 0.0, maxYRatio = 0.0;
for (size_t c = 0; c < 2; c++) {
double xHalfWidth = tan(glm::radians(pairs[i][c]->m_fovDegrees[0]) * 0.5) * depthForFOV;
double yHalfWidth = tan(glm::radians(pairs[i][c]->m_fovDegrees[1]) * 0.5) * depthForFOV;
std::array<double, 3> left = { -xHalfWidth, 0.0, -depthForFOV };
std::array<double, 3> right = { xHalfWidth, 0.0, -depthForFOV };
std::array<double, 3> top = { 0.0, yHalfWidth, -depthForFOV };
std::array<double, 3> bottom = { 0.0, -yHalfWidth, -depthForFOV };
std::array<double, 3> distortedLeft = pairs[i][c]->m_distortion->MapPoint(left);
std::array<double, 3> distortedRight = pairs[i][c]->m_distortion->MapPoint(right);
std::array<double, 3> distortedTop = pairs[i][c]->m_distortion->MapPoint(top);
std::array<double, 3> distortedBottom = pairs[i][c]->m_distortion->MapPoint(bottom);
double leftHFOV = glm::degrees(2.0 * atan(fabs(distortedLeft[0] / distortedLeft[2])));
double rightHFOV = glm::degrees(2.0 * atan(fabs(distortedRight[0] / distortedRight[2])));
double topVFOV = glm::degrees(2.0 * atan(fabs(distortedTop[1] / distortedTop[2])));
double bottomVFOV = glm::degrees(2.0 * atan(fabs(distortedBottom[1] / distortedBottom[2])));
double hFOV = std::min(leftHFOV, rightHFOV);
double vFOV = std::min(topVFOV, bottomVFOV);
minHFOV = std::min(minHFOV, hFOV);
minVFOV = std::min(minVFOV, vFOV);
maxXRatio = std::max(maxXRatio, std::min(fabs(distortedLeft[0]),fabs(distortedRight[0])) / xHalfWidth);
maxYRatio = std::max(maxYRatio, std::min(fabs(distortedTop[1]),fabs(distortedBottom[1])) / yHalfWidth);
}
// Reduce the FOVs by the difference in pointing direction of the two cameras, around the
// X axis for teh vertical FOV and around the Z axis for the horizontal FOV. This is to handle
// the fact that one will point further in each direction than the other.
double deltaX = fabs(pairs[i][0]->m_orientationDegrees[0] - pairs[i][1]->m_orientationDegrees[0]);
double deltaZ = fabs(pairs[i][0]->m_orientationDegrees[2] - pairs[i][1]->m_orientationDegrees[2]);
fovsDeg[0] = static_cast<float>(minHFOV - deltaZ);
fovsDeg[1] = static_cast<float>(minVFOV - deltaX);
// Use the ratio of the new and original fields of view to scale the pixel count, making sure that
// the results are an even multiple of the number of samples in X and Y.
std::array<unsigned, 2> pixelCounts;
uint16_t maxX = std::max(pairs[i][0]->m_resolutionPixels[0], pairs[i][1]->m_resolutionPixels[0]);
uint16_t maxY = std::max(pairs[i][0]->m_resolutionPixels[1], pairs[i][1]->m_resolutionPixels[1]);
pixelCounts[0] = static_cast<unsigned>(maxX * maxXRatio);
if (pixelCounts[0] % m_nx != 0) { pixelCounts[0] += m_nx - (pixelCounts[0] % m_nx); }
pixelCounts[1] = static_cast<unsigned>(maxY * maxYRatio);
if (pixelCounts[1] % m_ny != 0) { pixelCounts[1] += m_ny - (pixelCounts[1] % m_ny); }
//std::cout << "XXX Position: " << position.x << " " << position.y << " " << position.z
// << ", Orientation: " << orientation.w << " " << orientation.x << " " << orientation.y << " " << orientation.z
// << ", Pixel counts: " << pixelCounts[0] << " " << pixelCounts[1]
// << ", Regions: " << m_nx << " " << m_ny
// << std::endl;
// Make the camera pair info.
std::shared_ptr<CameraPairInfo> cameraPairInfo = std::make_shared<CameraPairInfo>(
toneMap, pairs[i][0], pairs[i][1], rangeEstimator,
position, orientation, fovsDeg, pixelCounts,
poseAdjuster, cameraFrameInterval, depths, m_defaultDepth);
if (!cameraPairInfo->m_constructorStatus.empty()) {
m_constructorStatus = cameraPairInfo->m_constructorStatus;
return;
}
m_cameraPairs.push_back(cameraPairInfo);
}
}
~DepthEstimatorImpl() {
// Done with all of the CUDA streams used per camera.
for (auto& pair : m_cameraStreams) {
cudaStreamDestroy(*pair.second);
delete pair.second;
}
}
std::string ComputeDepthEstimate(Time time)
{
#if !defined(NDEBUG)
GLenum err = glGetError();
if (err != GL_NO_ERROR) {
return "OpenGL error at start of ComputeDepthEstimate(): " + std::to_string(err);
}
#endif
// Push consistent images from both cameras onto their custom queue so that they
// will use consistent images to determine depth.
// Clear the image that we're finished with from the custom queues for the cameras.
std::map< std::shared_ptr<CameraPairInfo>,
std::pair< std::vector< std::shared_ptr<ImageData> >,
std::vector< std::shared_ptr<asdp::render::CameraRenderInfo> > > > consistentImageSets;
for (auto& pair : m_cameraPairs) {
std::shared_ptr<CameraRenderInfo> camera0 = pair->m_cameras[0];
std::shared_ptr<CameraRenderInfo> camera1 = pair->m_cameras[1];
// Push consistent images from both actual cameras onto the custom queues
// of all depth cameras so that they will use consistent images to determine depth.
// Clear a previous image that we're finished with from the custom queues for the cameras.
std::vector< std::shared_ptr<asdp::render::CameraRenderInfo> > cameras = { camera0, camera1 };
std::vector< std::shared_ptr<ImageData> > images = GetConsistentImageSet(cameras);
if (images.size() == 2) {
for (auto depth : pair->m_perDepths) {
depth.m_imageQueues[0]->InsertImage(images[0]);
depth.m_imageQueues[0]->GetOldestImage();
depth.m_imageQueues[1]->InsertImage(images[1]);
depth.m_imageQueues[1]->GetOldestImage();
}
} else {
return "Failed to get consistent images for cameras.";
}
// Keep track of the images and cameras for this pair so that we can unlock them
// after we're done with them.
consistentImageSets[pair].first.push_back(images[0]);
consistentImageSets[pair].second.push_back(camera0);
consistentImageSets[pair].first.push_back(images[1]);
consistentImageSets[pair].second.push_back(camera1);
}
// OpenGL fence objects to let us ensure that we're done with OpenGL rendering before we
// start to map the buffers to CUDA and do the depth estimation. There is one entry
// for each camera with one entry for each depth with an entry for each of the pair of cameras.
std::vector < std::vector< std::array<GLsync, 2> > > fences;
// For each camera pair and depth, render the two cameras into their frame buffers and keep track of the fences.
for (size_t c = 0; c < m_cameraPairs.size(); c++) {
CameraPairInfo& cpi = *m_cameraPairs[c];
std::vector< std::array<GLsync, 2> > cFences;
for (size_t d = 0; d < cpi.m_perDepths.size(); d++) {
std::array<GLsync, 2> dFences;
for (size_t b = 0; b < 2; b++) {
// Fill in the render info.
ViewRenderInfo vri;
for (size_t i = 0; i < 3; i++) {
vri.viewpoint[i] = static_cast<float>(cpi.m_position[i]);
}
// The vri.orientation quaternion is in WXYZ order, but the glm quaternion is in XYZW order.
vri.orientation[0] = static_cast<float>(cpi.m_orientation.w);
vri.orientation[1] = static_cast<float>(cpi.m_orientation.x);
vri.orientation[2] = static_cast<float>(cpi.m_orientation.y);
vri.orientation[3] = static_cast<float>(cpi.m_orientation.z);
vri.leftHalfFOV = -cpi.m_fovsDeg[0] / 2.0f;
vri.rightHalfFOV = cpi.m_fovsDeg[0] / 2.0f;
vri.bottomHalfFOV = -cpi.m_fovsDeg[1] / 2.0f;
vri.topHalfFOV = cpi.m_fovsDeg[1] / 2.0f;
vri.nearClip = cpi.m_perDepths[d].m_depth / 2;
vri.farClip = cpi.m_perDepths[d].m_depth * 2;
vri.frameBuffer = cpi.m_perDepths[d].m_frameBuffers[b];
vri.colorBuffer = cpi.m_perDepths[d].m_colorBuffers[b];
vri.depthBuffer = cpi.m_perDepths[d].m_depthBuffers[b];
vri.x = 0;
vri.y = 0;
vri.width = cpi.m_pixelCounts[0];
vri.height = cpi.m_pixelCounts[1];
// Render the composite camera and construct a fence to indicate completion.
#if !defined(NDEBUG)
err = glGetError();
if (err != GL_NO_ERROR) {
return "OpenGL error before Render() for pair " + std::to_string(c)
+ " depth " + std::to_string(d) + " camera " + std::to_string(b) + ": "
+ std::to_string(err);
}
#endif
cpi.m_perDepths[d].m_composites[b]->Render(time, {vri});
#if !defined(NDEBUG)
err = glGetError();
if (err != GL_NO_ERROR) {
return "OpenGL error before fence for pair " + std::to_string(c)
+ " depth " + std::to_string(d) + " camera " + std::to_string(b) + ": "
+ std::to_string(err);
}
#endif
dFences[b] = glFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0);
if (dFences[b] == nullptr) {
GLenum err = glGetError();
return "glFenceSync() failed for pair " + std::to_string(c)
+ " depth " + std::to_string(d) + " camera " + std::to_string(b)
+ ": error " + std::to_string(err);
}
}
cFences.push_back(dFences);
}
fences.push_back(cFences);
}
// Loop back through the camera pairs and depths, waiting for both fences to complete
// and then mapping the color buffers to CUDA and running the depth estimation.
for (size_t c = 0; c < m_cameraPairs.size(); c++) {
CameraPairInfo& cpi = *m_cameraPairs[c];
// The number of regions is the number of regions in X times the number of regions in Y.
size_t numRegions = m_nx * m_ny;
// Vector of surface objects to destroy once we're done with them.
std::vector<cudaSurfaceObject_t> surfObjs;
for (size_t d = 0; d < cpi.m_perDepths.size(); d++) {
CameraPairInfo::PerDepth &pd = cpi.m_perDepths[d];
// Wait for both fences to complete.
for (size_t b = 0; b < 2; b++) {
// 1-second timeout.
GLenum ret = glClientWaitSync(fences[c][d][b], 0, 1000000000);
if (ret != GL_ALREADY_SIGNALED && ret != GL_CONDITION_SATISFIED) {
return "glClientWaitSync() failed for pair " + std::to_string(c)
+ " depth " + std::to_string(d) + " camera " + std::to_string(b)
+ ": code " + std::to_string(ret);
}
}
// Map the color buffers to CUDA, using the already-registered images. Then get the
// mapped array values.
std::array< cudaArray*, 2> arrays;
for (size_t b = 0; b < 2; b++) {
#if 0
// Read back the texture to a CPU buffer.
{
// Check for OpenGL errors.
GLenum err = glGetError();
if (err != GL_NO_ERROR) {
return "OpenGL error before reading back texture for pair " + std::to_string(c)
+ " depth " + std::to_string(d) + " camera " + std::to_string(b) + ": "
+ std::to_string(err);
}
std::vector<uchar4> pixels(cpi.m_pixelCounts[0] * cpi.m_pixelCounts[1]);
glBindTexture(GL_TEXTURE_2D, pd.m_colorBuffers[b]);
glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels.data());
glBindTexture(GL_TEXTURE_2D, 0);
// Write a binary PPM (P6) file named for the camera pair, depth, and camera.
std::ofstream ppmFile("depthEstimator" + std::to_string(c) + "_" + std::to_string(d) + "_" + std::to_string(b) + ".ppm", std::ios::binary);
ppmFile << "P6\n" << cpi.m_pixelCounts[0] << " " << cpi.m_pixelCounts[1] << "\n255\n";
// Reuse a single row buffer to avoid per-pixel I/O
std::vector<unsigned char> rowBuf;
rowBuf.resize(static_cast<size_t>(cpi.m_pixelCounts[0]) * 3);
for (size_t y = 0; y < cpi.m_pixelCounts[1]; y++) {
// The texture has lower-left corner first, but the PPM file has upper-left first.
size_t flipY = (cpi.m_pixelCounts[1] - 1) - y;
for (size_t x = 0; x < cpi.m_pixelCounts[0]; x++) {
uchar4 val = pixels[x + flipY * cpi.m_pixelCounts[0]];
size_t idx = x * 3;
rowBuf[idx + 0] = static_cast<unsigned char>(val.x); // R
rowBuf[idx + 1] = static_cast<unsigned char>(val.y); // G
rowBuf[idx + 2] = static_cast<unsigned char>(val.z); // B
}
ppmFile.write(reinterpret_cast<const char*>(rowBuf.data()), rowBuf.size());
}
ppmFile.close();
}
#endif
cudaError_t res = cudaGraphicsMapResources(1, &pd.m_cudaColorBuffers[b], *(pd.m_stream));
if (res != cudaSuccess) {
return "cudaGraphicsMapResources() failed for pair " + std::to_string(c)
+ " depth " + std::to_string(d) + " camera " + std::to_string(b) + ": "
+ std::string(cudaGetErrorString(res));
}
res = cudaGraphicsSubResourceGetMappedArray(&arrays[b], pd.m_cudaColorBuffers[b], 0, 0);
if (res != cudaSuccess) {
return "cudaGraphicsSubResourceGetMappedArray() failed for pair " + std::to_string(c)
+ " depth " + std::to_string(d) + " camera " + std::to_string(b) + ": "