This repository has been archived by the owner on May 3, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 148
/
ServerTrackerView.cpp
2262 lines (1912 loc) · 77.9 KB
/
ServerTrackerView.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//-- includes -----
#include "DeviceEnumerator.h"
#include "DeviceManager.h"
#include "ServerTrackerView.h"
#include "ServerControllerView.h"
#include "ServerHMDView.h"
#include "MathUtility.h"
#include "MathEigen.h"
#include "MathGLM.h"
#include "MathAlignment.h"
#include "PS3EyeTracker.h"
#include "PSMoveProtocol.pb.h"
#include "ServerUtility.h"
#include "ServerLog.h"
#include "ServerRequestHandler.h"
#include "SharedTrackerState.h"
#include "TrackerManager.h"
#include <boost/interprocess/shared_memory_object.hpp>
#include <boost/interprocess/mapped_region.hpp>
#include <boost/interprocess/sync/scoped_lock.hpp>
#include <memory>
#include "opencv2/opencv.hpp"
#include "opencv2/calib3d/calib3d.hpp"
#define USE_OPEN_CV_ELLIPSE_FIT
//-- typedefs ----
typedef std::vector<cv::Point> t_opencv_contour;
typedef std::vector<t_opencv_contour> t_opencv_contour_list;
//-- private methods -----
class SharedVideoFrameReadWriteAccessor
{
public:
SharedVideoFrameReadWriteAccessor()
: m_shared_memory_object(nullptr)
, m_region(nullptr)
{}
~SharedVideoFrameReadWriteAccessor()
{
dispose();
}
bool initialize(const char *shared_memory_name, int width, int height, int stride)
{
bool bSuccess = false;
try
{
SERVER_LOG_INFO("SharedMemory::initialize()") << "Allocating shared memory: " << shared_memory_name;
// Remember the name of the shared memory
m_shared_memory_name = shared_memory_name;
// Make sure the shared memory block has been removed first
boost::interprocess::shared_memory_object::remove(shared_memory_name);
// Allow non admin-level processed to access the shared memory
boost::interprocess::permissions permissions;
permissions.set_unrestricted();
// Create the shared memory object
m_shared_memory_object =
new boost::interprocess::shared_memory_object(
boost::interprocess::create_only,
shared_memory_name,
boost::interprocess::read_write,
permissions);
// Resize the shared memory
m_shared_memory_object->truncate(SharedVideoFrameHeader::computeTotalSize(stride, width));
// Map all of the shared memory for read/write access
m_region = new boost::interprocess::mapped_region(*m_shared_memory_object, boost::interprocess::read_write);
// Initialize the shared memory (call constructor using placement new)
// This make sure the mutex has the constructor called on it.
SharedVideoFrameHeader *frameState = new (getFrameHeader()) SharedVideoFrameHeader();
frameState->width = width;
frameState->height = height;
frameState->stride = stride;
frameState->frame_index = 0;
std::memset(
frameState->getBufferMutable(),
0,
SharedVideoFrameHeader::computeVideoBufferSize(stride, height));
bSuccess = true;
}
catch (boost::interprocess::interprocess_exception* e)
{
dispose();
SERVER_LOG_ERROR("SharedMemory::initialize()") << "Failed to allocated shared memory: " << m_shared_memory_name
<< ", reason: " << e->what();
}
return bSuccess;
}
void dispose()
{
if (m_region != nullptr)
{
// Call the destructor manually on the frame header since it was constructed via placement new
// This will make sure the mutex has the destructor called on it.
getFrameHeader()->~SharedVideoFrameHeader();
delete m_region;
m_region = nullptr;
}
if (m_shared_memory_object != nullptr)
{
delete m_shared_memory_object;
m_shared_memory_object = nullptr;
}
if (!boost::interprocess::shared_memory_object::remove(m_shared_memory_name))
{
SERVER_LOG_ERROR("SharedMemory::dispose") << "Failed to free shared memory: " << m_shared_memory_name;
}
}
void writeVideoFrame(const unsigned char *buffer)
{
SharedVideoFrameHeader *sharedFrameState = getFrameHeader();
boost::interprocess::scoped_lock<boost::interprocess::interprocess_mutex> lock(sharedFrameState->mutex);
size_t buffer_size =
SharedVideoFrameHeader::computeVideoBufferSize(sharedFrameState->stride, sharedFrameState->height);
size_t total_shared_mem_size =
SharedVideoFrameHeader::computeTotalSize(sharedFrameState->stride, sharedFrameState->height);
assert(m_region->get_size() >= total_shared_mem_size);
++sharedFrameState->frame_index;
std::memcpy(sharedFrameState->getBufferMutable(), buffer, buffer_size);
}
protected:
SharedVideoFrameHeader *getFrameHeader()
{
return reinterpret_cast<SharedVideoFrameHeader *>(m_region->get_address());
}
private:
const char *m_shared_memory_name;
boost::interprocess::shared_memory_object *m_shared_memory_object;
boost::interprocess::mapped_region *m_region;
};
struct OpenCVPlane2D
{
cv::Point2f origin;
cv::Point3f coefficients; // coefficients a, b, c in 2d plane equation: a*x + b*y + c = 0
OpenCVPlane2D()
: origin(0.f, 0.f)
, coefficients(0.f, 0.f, 0.f)
{
}
OpenCVPlane2D(
const cv::Point2f &o,
const cv::Point3f &c)
: origin(o)
, coefficients(c)
{
}
static OpenCVPlane2D createFromPoints(const cv::Point2f &a, const cv::Point2f &b, const cv::Point2f &inside)
{
const cv::Point2f tangent= b - a;
const float tangent_length= static_cast<float>(cv::norm(tangent));
cv::Point2f normal=
!is_nearly_zero(tangent_length)
? cv::Point2f(-tangent.y/tangent_length, tangent.x/tangent_length)
: cv::Point2f(0.f, 0.f);
// Make sure the "inside point" is on the positive side of the plane
if ((inside - a).dot(normal) < 0)
{
normal= -normal;
}
const cv::Point2f center= (a + b) / 2.f;
return OpenCVPlane2D::createFromPointAndNormal(center, normal);
}
static OpenCVPlane2D createFromPointAndNormal(const cv::Point2f &p, const cv::Point2f &n)
{
const float n_length= static_cast<float>(cv::norm(n));
const cv::Point2f normal= !is_nearly_zero(n_length) ? (n / n_length) : cv::Point2f(0.f, 0.f);
cv::Point3f coefficients;
coefficients.x= normal.x; // coefficient a
coefficients.y= normal.y; // coefficient b
coefficients.z= -normal.dot(p); // coefficient c
return OpenCVPlane2D(p, coefficients);
}
inline cv::Point2f getOrigin() const
{
return origin;
}
inline cv::Point2f getNormal() const
{
return cv::Point2f(coefficients.x, coefficients.y);
}
inline bool isValidPlane() const
{
return !is_nearly_zero(coefficients.x) || !is_nearly_zero(coefficients.y);
}
float signedDistance(const cv::Point2f &point) const
{
return point.x*coefficients.x + point.y*coefficients.y + coefficients.z;
}
float unsignedDistance(const cv::Point2f &point) const
{
return fabsf(signedDistance(point));
}
cv::Point2f computeTangent() const
{
return cv::Point2f(-coefficients.y, coefficients.x);
}
};
class OpenCVBGRToHSVMapper
{
public:
typedef cv::Point3_<uint8_t> ColorTuple;
static OpenCVBGRToHSVMapper *allocate()
{
if (m_refCount == 0)
{
assert(m_instance == nullptr);
m_instance = new OpenCVBGRToHSVMapper();
}
assert(m_instance != nullptr);
++m_refCount;
return m_instance;
}
static void dispose(OpenCVBGRToHSVMapper *instance)
{
assert(m_instance != nullptr);
assert(m_instance == instance);
assert(m_refCount > 0);
--m_refCount;
if (m_refCount <= 0)
{
delete m_instance;
m_instance = nullptr;
}
}
void cvtColor(const cv::Mat &bgrBuffer, cv::Mat &hsvBuffer)
{
hsvBuffer.forEach<ColorTuple>([&bgrBuffer, this](ColorTuple &hsvColor, const int position[]) -> void {
const ColorTuple &bgrColor = bgrBuffer.at<ColorTuple>(position[0], position[1]);
const int b = bgrColor.x;
const int g = bgrColor.y;
const int r = bgrColor.z;
const int LUTIndex = OpenCVBGRToHSVMapper::getLUTIndex(r, g, b);
hsvColor = bgr2hsv->at<ColorTuple>(LUTIndex, 0);
});
}
private:
static OpenCVBGRToHSVMapper *m_instance;
static int m_refCount;
OpenCVBGRToHSVMapper()
{
bgr2hsv = new cv::Mat(256*256*256, 1, CV_8UC3);
int LUTIndex = 0;
for (int r = 0; r < 256; ++r)
{
for (int g = 0; g < 256; ++g)
{
for (int b = 0; b < 256; ++b)
{
bgr2hsv->at<ColorTuple>(LUTIndex, 0) = ColorTuple(b, g, r);
++LUTIndex;
}
}
}
cv::cvtColor(*bgr2hsv, *bgr2hsv, cv::COLOR_BGR2HSV);
}
~OpenCVBGRToHSVMapper()
{
delete bgr2hsv;
}
static int getLUTIndex(int r, int g, int b)
{
return (256 * 256)*r + 256*g + b;
}
cv::Mat *bgr2hsv;
};
OpenCVBGRToHSVMapper *OpenCVBGRToHSVMapper::m_instance = nullptr;
int OpenCVBGRToHSVMapper::m_refCount= 0;
class OpenCVBufferState
{
public:
OpenCVBufferState(ITrackerInterface *device)
: bgrBuffer(nullptr)
, bgrUndistortBuffer(nullptr)
, hsvBuffer(nullptr)
, gsLowerBuffer(nullptr)
, gsUpperBuffer(nullptr)
, maskedBuffer(nullptr)
, distortionMapX(nullptr)
, distortionMapY(nullptr)
{
device->getVideoFrameDimensions(&frameWidth, &frameHeight, nullptr);
bgrBuffer = new cv::Mat(frameHeight, frameWidth, CV_8UC3);
bgrUndistortBuffer = new cv::Mat(frameHeight, frameWidth, CV_8UC3);
hsvBuffer = new cv::Mat(frameHeight, frameWidth, CV_8UC3);
gsLowerBuffer = new cv::Mat(frameHeight, frameWidth, CV_8UC1);
gsUpperBuffer = new cv::Mat(frameHeight, frameWidth, CV_8UC1);
maskedBuffer = new cv::Mat(frameHeight, frameWidth, CV_8UC3);
intrinsic_matrix = new cv::Mat(3, 3, CV_64FC1);
distortion_coeffs = new cv::Mat(5, 1, CV_64FC1);
distortionMapX = new cv::Mat(cv::Size(frameWidth, frameHeight), CV_32FC1);
distortionMapY = new cv::Mat(cv::Size(frameWidth, frameHeight), CV_32FC1);
rebuildDistortionMap(device);
const TrackerManagerConfig &cfg= DeviceManager::getInstance()->m_tracker_manager->getConfig();
if (cfg.use_bgr_to_hsv_lookup_table)
{
bgr2hsv = OpenCVBGRToHSVMapper::allocate();
}
else
{
bgr2hsv = nullptr;
}
}
virtual ~OpenCVBufferState()
{
if (maskedBuffer != nullptr)
{
delete maskedBuffer;
}
if (gsLowerBuffer != nullptr)
{
delete gsLowerBuffer;
}
if (gsUpperBuffer != nullptr)
{
delete gsUpperBuffer;
}
if (hsvBuffer != nullptr)
{
delete hsvBuffer;
}
if (bgrBuffer != nullptr)
{
delete bgrBuffer;
}
if (bgrUndistortBuffer != nullptr)
{
delete bgrUndistortBuffer;
}
// TODO: If not nullptr wrapper
delete intrinsic_matrix;
delete distortion_coeffs;
delete distortionMapX;
delete distortionMapY;
if (bgr2hsv != nullptr)
{
OpenCVBGRToHSVMapper::dispose(bgr2hsv);
}
}
void rebuildDistortionMap(ITrackerInterface *device)
{
float F_PX, F_PY;
float PrincipalX, PrincipalY;
float distortionK1, distortionK2, distortionK3;
float distortionP1, distortionP2;
device->getCameraIntrinsics(
F_PX, F_PY,
PrincipalX, PrincipalY,
distortionK1, distortionK2, distortionK3,
distortionP1, distortionP2);
// Fill in the intrinsic matrix
intrinsic_matrix->at<double>(0, 0)= F_PX;
intrinsic_matrix->at<double>(1, 0)= 0.0;
intrinsic_matrix->at<double>(2, 0)= 0.0;
intrinsic_matrix->at<double>(0, 1)= 0.0;
intrinsic_matrix->at<double>(1, 1)= F_PY;
intrinsic_matrix->at<double>(2, 1)= 0.0;
intrinsic_matrix->at<double>(0, 2)= PrincipalX;
intrinsic_matrix->at<double>(1, 2)= PrincipalY;
intrinsic_matrix->at<double>(2, 2)= 1.0;
// Fill in the distortion coefficients
distortion_coeffs->at<double>(0, 0)= distortionK1;
distortion_coeffs->at<double>(1, 0)= distortionK2;
distortion_coeffs->at<double>(2, 0)= distortionP1;
distortion_coeffs->at<double>(3, 0)= distortionP2;
distortion_coeffs->at<double>(4, 0)= distortionK3;
cv::initUndistortRectifyMap(
*intrinsic_matrix, *distortion_coeffs,
cv::noArray(), // unneeded rectification transformation computed by stereoRectify()
// newCameraMatrix - can be computed by getOptimalNewCameraMatrix(), but
*intrinsic_matrix, // "In case of a monocular camera, newCameraMatrix is usually equal to cameraMatrix"
cv::Size(frameWidth, frameHeight),
CV_32FC1, // Distortion map type
*distortionMapX, *distortionMapY);
}
void writeVideoFrame(const unsigned char *video_buffer)
{
const cv::Mat videoBufferMat(frameHeight, frameWidth, CV_8UC3, const_cast<unsigned char *>(video_buffer));
videoBufferMat.copyTo(*bgrBuffer);
// Apply the distortion map to the source video frame
cv::remap(
*bgrBuffer, *bgrUndistortBuffer,
*distortionMapX, *distortionMapY,
cv::INTER_LINEAR, cv::BORDER_CONSTANT);
// Convert the video buffer to the HSV color space
if (bgr2hsv != nullptr)
{
bgr2hsv->cvtColor(*bgrUndistortBuffer, *hsvBuffer);
}
else
{
cv::cvtColor(*bgrUndistortBuffer, *hsvBuffer, cv::COLOR_BGR2HSV);
}
}
// Return points in raw image space:
// i.e. [0, 0] at lower left to [frameWidth-1, frameHeight-1] at lower right
bool computeBiggestNContours(
const CommonHSVColorRange &hsvColorRange,
t_opencv_contour_list &out_biggest_N_contours,
const int max_contour_count)
{
// Clamp the HSV image, taking into account wrapping the hue angle
{
const float hue_min = hsvColorRange.hue_range.center - hsvColorRange.hue_range.range;
const float hue_max = hsvColorRange.hue_range.center + hsvColorRange.hue_range.range;
const float saturation_min = clampf(hsvColorRange.saturation_range.center - hsvColorRange.saturation_range.range, 0, 255);
const float saturation_max = clampf(hsvColorRange.saturation_range.center + hsvColorRange.saturation_range.range, 0, 255);
const float value_min = clampf(hsvColorRange.value_range.center - hsvColorRange.value_range.range, 0, 255);
const float value_max = clampf(hsvColorRange.value_range.center + hsvColorRange.value_range.range, 0, 255);
if (hue_min < 0)
{
cv::inRange(
*hsvBuffer,
cv::Scalar(0, saturation_min, value_min),
cv::Scalar(clampf(hue_max, 0, 180), saturation_max, value_max),
*gsLowerBuffer);
cv::inRange(
*hsvBuffer,
cv::Scalar(clampf(180 + hue_min, 0, 180), saturation_min, value_min),
cv::Scalar(180, saturation_max, value_max),
*gsUpperBuffer);
cv::bitwise_or(*gsLowerBuffer, *gsUpperBuffer, *gsLowerBuffer);
}
else if (hue_max > 180)
{
cv::inRange(
*hsvBuffer,
cv::Scalar(0, saturation_min, value_min),
cv::Scalar(clampf(hue_max - 180, 0, 180), saturation_max, value_max),
*gsLowerBuffer);
cv::inRange(
*hsvBuffer,
cv::Scalar(clampf(hue_min, 0, 180), saturation_min, value_min),
cv::Scalar(180, saturation_max, value_max),
*gsUpperBuffer);
cv::bitwise_or(*gsLowerBuffer, *gsUpperBuffer, *gsLowerBuffer);
}
else
{
cv::inRange(
*hsvBuffer,
cv::Scalar(hue_min, saturation_min, value_min),
cv::Scalar(hue_max, saturation_max, value_max),
*gsLowerBuffer);
}
}
// Find the largest convex blob in the filtered grayscale buffer
{
struct ContourInfo
{
int contour_index;
double contour_area;
};
std::vector<ContourInfo> sorted_contour_list;
// Find all counters in the image buffer
t_opencv_contour_list contours;
cv::findContours(*gsLowerBuffer, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE);
// Compute the area of each contour
int contour_index = 0;
for (auto it = contours.begin(); it != contours.end(); ++it)
{
const double contour_area = cv::contourArea(*it);
const ContourInfo contour_info = { contour_index, contour_area };
sorted_contour_list.push_back(contour_info);
++contour_index;
}
// Sort the list of contours by area, largest to smallest
if (sorted_contour_list.size() > 1)
{
std::sort(
sorted_contour_list.begin(), sorted_contour_list.end(),
[](const ContourInfo &a, const ContourInfo &b) {
return b.contour_area < a.contour_area;
});
}
// Copy up to N valid contours
for (auto it = sorted_contour_list.begin();
it != sorted_contour_list.end() && static_cast<int>(out_biggest_N_contours.size()) < max_contour_count;
++it)
{
const ContourInfo &contour_info = *it;
t_opencv_contour &contour = contours[contour_info.contour_index];
if (contour.size() > 6)
{
// Remove any points in contour on edge of camera/ROI
t_opencv_contour::iterator it = contour.begin();
while (it != contour.end())
{
if (it->x == 0 || it->x == (frameWidth - 1) || it->y == 0 || it->y == (frameHeight - 1))
{
it = contour.erase(it);
}
else
{
++it;
}
}
// Add cleaned up contour to the output list
out_biggest_N_contours.push_back(contour);
}
}
}
return (out_biggest_N_contours.size() > 0);
}
int frameWidth;
int frameHeight;
cv::Mat *bgrBuffer; // source video frame
cv::Mat *bgrUndistortBuffer; // undistorted source video frame
cv::Mat *hsvBuffer; // source frame converted to HSV color space
cv::Mat *gsLowerBuffer; // HSV image clamped by HSV range into grayscale mask
cv::Mat *gsUpperBuffer; // HSV image clamped by HSV range into grayscale mask
cv::Mat *maskedBuffer; // bgr image ANDed together with grayscale mask
cv::Mat *intrinsic_matrix;
cv::Mat *distortion_coeffs;
cv::Mat *distortionMapX;
cv::Mat *distortionMapY;
OpenCVBGRToHSVMapper *bgr2hsv; // Used to convert an rgb image to an hsv image
};
// -- Utility Methods -----
static glm::quat computeGLMCameraTransformQuaternion(const ITrackerInterface *tracker_device);
static glm::mat4 computeGLMCameraTransformMatrix(const ITrackerInterface *tracker_device);
static cv::Matx34f computeOpenCVCameraExtrinsicMatrix(const ITrackerInterface *tracker_device);
static cv::Matx33f computeOpenCVCameraIntrinsicMatrix(const ITrackerInterface *tracker_device);
static cv::Matx34f computeOpenCVCameraPinholeMatrix(const ITrackerInterface *tracker_device);
static bool computeTrackerRelativeLightBarProjection(
const ITrackerInterface *tracker_device,
const CommonDeviceTrackingShape *tracking_shape,
const t_opencv_contour &opencv_contour,
CommonDeviceTrackingProjection *out_projection);
static bool computeTrackerRelativeLightBarPose(
const ITrackerInterface *tracker_device,
const CommonDeviceTrackingShape *tracking_shape,
const CommonDeviceTrackingProjection *projection,
const CommonDevicePose *tracker_relative_pose_guess,
ControllerOpticalPoseEstimation *out_pose_estimate);
static bool computeTrackerRelativePointCloudContourPose(
const ITrackerInterface *tracker_device,
const CommonDeviceTrackingShape *tracking_shape,
const t_opencv_contour_list &opencv_contours,
const CommonDevicePose *tracker_relative_pose_guess,
HMDOpticalPoseEstimation *out_pose_estimate);
static bool computeBestFitTriangleForContour(
const t_opencv_contour &opencv_contour,
cv::Point2f &out_triangle_top,
cv::Point2f &out_triangle_bottom_left,
cv::Point2f &out_triangle_bottom_right);
static bool computeBestFitQuadForContour(
const t_opencv_contour &opencv_contour,
const cv::Point2f &up_hint,
const cv::Point2f &right_hint,
cv::Point2f &top_right,
cv::Point2f &top_left,
cv::Point2f &bottom_left,
cv::Point2f &bottom_right);
static void commonDeviceOrientationToOpenCVRodrigues(
const CommonDeviceQuaternion &orientation,
cv::Mat &rvec);
static void openCVRodriguesToAngleAxis(
const cv::Mat &rvec,
float &axis_x, float &axis_y, float &axis_z, float &radians);
static void angleAxisVectorToEulerAngles(
const float axis_x, const float axis_y, const float axis_z, const float radians,
float &yaw, float &pitch, float &roll);
static void angleAxisVectorToCommonDeviceOrientation(
const float axis_x, const float axis_y, const float axis_z, const float radians,
CommonDeviceQuaternion &orientation);
//-- public implementation -----
ServerTrackerView::ServerTrackerView(const int device_id)
: ServerDeviceView(device_id)
, m_shared_memory_accesor(nullptr)
, m_shared_memory_video_stream_count(0)
, m_opencv_buffer_state(nullptr)
, m_device(nullptr)
{
ServerUtility::format_string(m_shared_memory_name, sizeof(m_shared_memory_name), "tracker_view_%d", device_id);
}
ServerTrackerView::~ServerTrackerView()
{
if (m_shared_memory_accesor != nullptr)
{
delete m_shared_memory_accesor;
}
if (m_opencv_buffer_state != nullptr)
{
delete m_opencv_buffer_state;
}
if (m_device != nullptr)
{
delete m_device;
}
}
CommonDeviceState::eDeviceType
ServerTrackerView::getTrackerDeviceType() const
{
return m_device->getDeviceType();
}
ITrackerInterface::eDriverType
ServerTrackerView::getTrackerDriverType() const
{
return m_device->getDriverType();
}
std::string
ServerTrackerView::getUSBDevicePath() const
{
return m_device->getUSBDevicePath();
}
std::string
ServerTrackerView::getSharedMemoryStreamName() const
{
return std::string(m_shared_memory_name);
}
bool ServerTrackerView::open(const class DeviceEnumerator *enumerator)
{
bool bSuccess = ServerDeviceView::open(enumerator);
if (bSuccess)
{
int width, height, stride;
// Make sure the shared memory block has been removed first
boost::interprocess::shared_memory_object::remove(m_shared_memory_name);
// Query the video frame first so that we know how big to make the buffer
if (m_device->getVideoFrameDimensions(&width, &height, &stride))
{
assert(m_shared_memory_accesor == nullptr);
m_shared_memory_accesor = new SharedVideoFrameReadWriteAccessor();
if (!m_shared_memory_accesor->initialize(m_shared_memory_name, width, height, stride))
{
delete m_shared_memory_accesor;
m_shared_memory_accesor = nullptr;
SERVER_LOG_ERROR("ServerTrackerView::open()") << "Failed to allocated shared memory: " << m_shared_memory_name;
}
// Allocate the OpenCV scratch buffers used for finding tracking blobs
m_opencv_buffer_state = new OpenCVBufferState(m_device);
}
else
{
SERVER_LOG_ERROR("ServerTrackerView::open()") << "Failed to video frame dimensions";
}
}
return bSuccess;
}
void ServerTrackerView::close()
{
if (m_shared_memory_accesor != nullptr)
{
delete m_shared_memory_accesor;
m_shared_memory_accesor = nullptr;
}
ServerDeviceView::close();
}
void ServerTrackerView::startSharedMemoryVideoStream()
{
++m_shared_memory_video_stream_count;
}
void ServerTrackerView::stopSharedMemoryVideoStream()
{
assert(m_shared_memory_video_stream_count > 0);
--m_shared_memory_video_stream_count;
}
bool ServerTrackerView::poll()
{
bool bSuccess = ServerDeviceView::poll();
if (bSuccess && m_device != nullptr)
{
const unsigned char *buffer = m_device->getVideoFrameBuffer();
if (buffer != nullptr)
{
// Cache the raw video frame and convert it to an HSV buffer for filtering later
if (m_opencv_buffer_state != nullptr)
{
m_opencv_buffer_state->writeVideoFrame(buffer);
// Copy the video frame to shared memory (if requested)
if (m_shared_memory_accesor != nullptr && m_shared_memory_video_stream_count > 0)
{
m_shared_memory_accesor->writeVideoFrame(m_opencv_buffer_state->bgrBuffer->data);
}
}
}
}
return bSuccess;
}
bool ServerTrackerView::allocate_device_interface(const class DeviceEnumerator *enumerator)
{
switch (enumerator->get_device_type())
{
case CommonDeviceState::PS3EYE:
{
m_device = new PS3EyeTracker();
} break;
default:
break;
}
return m_device != nullptr;
}
void ServerTrackerView::free_device_interface()
{
if (m_device != nullptr)
{
delete m_device; // Deleting abstract object should be OK because
// this (ServerDeviceView) is abstract as well.
// All non-abstract children will have non-abstract types
// for m_device.
m_device = nullptr;
}
}
void ServerTrackerView::publish_device_data_frame()
{
// Tell the server request handler we want to send out tracker updates.
// This will call generate_tracker_data_frame_for_stream for each listening connection.
ServerRequestHandler::get_instance()->publish_tracker_data_frame(
this, &ServerTrackerView::generate_tracker_data_frame_for_stream);
}
void ServerTrackerView::generate_tracker_data_frame_for_stream(
const ServerTrackerView *tracker_view,
const struct TrackerStreamInfo *stream_info,
DeviceOutputDataFramePtr &data_frame)
{
PSMoveProtocol::DeviceOutputDataFrame_TrackerDataPacket *tracker_data_frame =
data_frame->mutable_tracker_data_packet();
tracker_data_frame->set_tracker_id(tracker_view->getDeviceID());
tracker_data_frame->set_sequence_num(tracker_view->m_sequence_number);
tracker_data_frame->set_isconnected(tracker_view->getIsOpen());
switch (tracker_view->getTrackerDeviceType())
{
case CommonDeviceState::PS3EYE:
{
//TODO: PS3EYE tracker location
} break;
default:
assert(0 && "Unhandled Tracker type");
}
data_frame->set_device_category(PSMoveProtocol::DeviceOutputDataFrame::TRACKER);
}
void ServerTrackerView::loadSettings()
{
m_device->loadSettings();
}
void ServerTrackerView::saveSettings()
{
m_device->saveSettings();
}
double ServerTrackerView::getExposure() const
{
return m_device->getExposure();
}
void ServerTrackerView::setExposure(double value)
{
m_device->setExposure(value);
}
double ServerTrackerView::getGain() const
{
return m_device->getGain();
}
void ServerTrackerView::setGain(double value)
{
m_device->setGain(value);
}
void ServerTrackerView::getCameraIntrinsics(
float &outFocalLengthX, float &outFocalLengthY,
float &outPrincipalX, float &outPrincipalY,
float &outDistortionK1, float &outDistortionK2, float &outDistortionK3,
float &outDistortionP1, float &outDistortionP2) const
{
m_device->getCameraIntrinsics(
outFocalLengthX, outFocalLengthY,
outPrincipalX, outPrincipalY,
outDistortionK1, outDistortionK2, outDistortionK3,
outDistortionP1, outDistortionP2);
}
void ServerTrackerView::setCameraIntrinsics(
float focalLengthX, float focalLengthY,
float principalX, float principalY,
float distortionK1, float distortionK2, float distortionK3,
float distortionP1, float distortionP2)
{
m_device->setCameraIntrinsics(
focalLengthX, focalLengthY,
principalX, principalY,
distortionK1, distortionK2, distortionK3,
distortionP1, distortionP2);
m_opencv_buffer_state->rebuildDistortionMap(m_device);
}
CommonDevicePose ServerTrackerView::getTrackerPose() const
{
return m_device->getTrackerPose();
}
void ServerTrackerView::setTrackerPose(
const struct CommonDevicePose *pose)
{
m_device->setTrackerPose(pose);
}
void ServerTrackerView::getPixelDimensions(float &outWidth, float &outHeight) const
{
int pixelWidth, pixelHeight;
m_device->getVideoFrameDimensions(&pixelWidth, &pixelHeight, nullptr);
outWidth = static_cast<float>(pixelWidth);
outHeight = static_cast<float>(pixelHeight);
}
void ServerTrackerView::getFOV(float &outHFOV, float &outVFOV) const
{
m_device->getFOV(outHFOV, outVFOV);
}
void ServerTrackerView::getZRange(float &outZNear, float &outZFar) const
{
m_device->getZRange(outZNear, outZFar);
}
void ServerTrackerView::gatherTrackerOptions(PSMoveProtocol::Response_ResultTrackerSettings* settings) const
{
m_device->gatherTrackerOptions(settings);
}
bool ServerTrackerView::setOptionIndex(const std::string &option_name, int option_index)
{
return m_device->setOptionIndex(option_name, option_index);
}
bool ServerTrackerView::getOptionIndex(const std::string &option_name, int &out_option_index) const
{
return m_device->getOptionIndex(option_name, out_option_index);
}
void ServerTrackerView::gatherTrackingColorPresets(
const class ServerControllerView *controller,
PSMoveProtocol::Response_ResultTrackerSettings* settings) const
{
std::string controller_id= (controller != nullptr) ? controller->getConfigIdentifier() : "";
return m_device->gatherTrackingColorPresets(controller_id, settings);
}
void ServerTrackerView::gatherTrackingColorPresets(
const class ServerHMDView *hmd,
PSMoveProtocol::Response_ResultTrackerSettings* settings) const
{
std::string hmd_id = (hmd != nullptr) ? hmd->getConfigIdentifier() : "";
return m_device->gatherTrackingColorPresets(hmd_id, settings);
}
void ServerTrackerView::setControllerTrackingColorPreset(
const class ServerControllerView *controller,
eCommonTrackingColorID color,
const CommonHSVColorRange *preset)
{
std::string controller_id= (controller != nullptr) ? controller->getConfigIdentifier() : "";
return m_device->setTrackingColorPreset(controller_id, color, preset);
}
void ServerTrackerView::getControllerTrackingColorPreset(
const class ServerControllerView *controller,
eCommonTrackingColorID color,
CommonHSVColorRange *out_preset) const
{
std::string controller_id= (controller != nullptr) ? controller->getConfigIdentifier() : "";
return m_device->getTrackingColorPreset(controller_id, color, out_preset);
}
void ServerTrackerView::setHMDTrackingColorPreset(