/
ofxKinect.cpp
732 lines (585 loc) · 19.9 KB
/
ofxKinect.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
/*==============================================================================
Copyright (c) 2010, 2011 ofxKinect Team
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
==============================================================================*/
#include "ofxKinect.h"
#include "ofMain.h"
#include "libfreenect-registration.h"
// context static
ofxKinectContext ofxKinect::kinectContext;
//--------------------------------------------------------------------
ofxKinect::ofxKinect() {
ofLog(OF_LOG_VERBOSE, "ofxKinect: Creating ofxKinect");
bUseTexture = true;
bGrabVideo = true;
// set defaults
bGrabberInited = false;
depthPixelsRaw = NULL;
depthPixelsBack = NULL;
videoPixels = NULL;
videoPixelsBack = NULL;
bNeedsUpdate = false;
bUpdateTex = false;
bIsFrameNew = false;
kinectDevice = NULL;
targetTiltAngleDeg = 0;
currentTiltAngleDeg = 0;
bTiltNeedsApplying = false;
bUseRegistration = false;
bNearWhite = true;
setDepthClipping();
}
//--------------------------------------------------------------------
ofxKinect::~ofxKinect() {
close();
clear();
}
//--------------------------------------------------------------------
bool ofxKinect::init(bool infrared, bool video, bool texture) {
if(isConnected()) {
ofLog(OF_LOG_WARNING, "ofxKinect: Do not call init while ofxKinect is running!");
return false;
}
clear();
bInfrared = infrared;
bGrabVideo = video;
bytespp = infrared?1:3;
bUseTexture = texture;
int length = width*height;
depthPixelsRaw = new unsigned short[length];
depthPixelsBack = new unsigned short[length];
videoPixels = new unsigned char[length*bytespp];
pixels.setFromExternalPixels(videoPixels, width, height, OF_IMAGE_COLOR);
videoPixelsBack = new unsigned char[length*bytespp];
depthPixels = new unsigned char[length * bytespp];
distancePixels = new float[length];
memset(depthPixelsRaw, 0, length*sizeof(unsigned short));
memset(depthPixelsBack, 0, length*sizeof(unsigned short));
memset(videoPixels, 0, length*bytespp*sizeof(unsigned char));
memset(videoPixelsBack, 0, length*bytespp*sizeof(unsigned char));
if(bUseTexture) {
depthTex.allocate(width, height, GL_LUMINANCE);
videoTex.allocate(width, height, infrared ? GL_LUMINANCE : GL_RGB);
}
if(!kinectContext.isInited()) {
if(!kinectContext.init()) {
return false;
}
}
ofLog(OF_LOG_VERBOSE, "ofxKinect: Number of devices found: %d", kinectContext.numTotal());
ofLog(OF_LOG_VERBOSE, "ofxKinect: Number of available devices: %d", kinectContext.numAvailable());
bGrabberInited = true;
return bGrabberInited;
}
//---------------------------------------------------------------------------
void ofxKinect::clear() {
if(isConnected()) {
ofLog(OF_LOG_WARNING, "ofxKinect: Do not call clear while ofxKinect is running!");
return;
}
if(kinectContext.numConnected() < 1) {
kinectContext.clear();
}
if(depthPixelsRaw != NULL){
delete[] depthPixelsRaw; depthPixelsRaw = NULL;
delete[] depthPixelsBack; depthPixelsBack = NULL;
delete[] videoPixels; videoPixels = NULL;
delete[] videoPixelsBack; videoPixelsBack = NULL;
delete [] depthPixels; depthPixels = NULL;
delete [] distancePixels; distancePixels = NULL;
}
depthTex.clear();
videoTex.clear();
bGrabberInited = false;
}
//--------------------------------------------------------------------
void ofxKinect::setRegistration(bool bUseRegistration) {
this->bUseRegistration = bUseRegistration;
}
//--------------------------------------------------------------------
bool ofxKinect::open(int id){
if(!bGrabberInited) {
ofLog(OF_LOG_WARNING, "ofxKinect: Cannot open, init not called");
return false;
}
if(kinectContext.numAvailable() < 1) {
ofLog(OF_LOG_ERROR, "ofxKinect: No available devices found");
return false;
}
if(!kinectContext.open(*this, id)) {
return false;
}
freenect_set_user(kinectDevice, this);
freenect_set_depth_callback(kinectDevice, &grabDepthFrame);
freenect_set_video_callback(kinectDevice, &grabRgbFrame);
startThread(true, false); // blocking, not verbose
return true;
}
//---------------------------------------------------------------------------
void ofxKinect::close() {
if(isThreadRunning()) {
waitForThread(true);
}
bIsFrameNew = false;
bNeedsUpdate = false;
bUpdateTex = false;
}
//---------------------------------------------------------------------------
bool ofxKinect::isConnected() {
return isThreadRunning();
}
//--------------------------------------------------------------------
bool ofxKinect::isFrameNew() {
if(isThreadRunning()) {
bool curIsFrameNew = bIsFrameNew;
bIsFrameNew = false;
return curIsFrameNew;
}
return false;
}
//----------------------------------------------------------
void ofxKinect::update() {
if(!bGrabberInited) {
return;
}
if(!bNeedsUpdate) {
return;
} else {
bIsFrameNew = true;
bUpdateTex = true;
}
if(this->lock()) {
int n = width * height;
memcpy(depthPixelsRaw, depthPixelsBack, n * sizeof(short));
memcpy(videoPixels, videoPixelsBack, n * bytespp);
//we have done the update
bNeedsUpdate = false;
this->unlock();
updateDepthPixels();
}
if(bUseTexture) {
depthTex.loadData(depthPixels, width, height, GL_LUMINANCE);
videoTex.loadData(videoPixels, width, height, bInfrared ? GL_LUMINANCE : GL_RGB);
bUpdateTex = false;
}
}
//------------------------------------
float ofxKinect::getDistanceAt(int x, int y) {
return depthPixelsRaw[y * width + x];
}
//------------------------------------
float ofxKinect::getDistanceAt(const ofPoint & p) {
return getDistanceAt(p.x, p.y);
}
//------------------------------------
ofVec3f ofxKinect::getWorldCoordinateAt(int x, int y) {
return getWorldCoordinateAt(x, y, getDistanceAt(x, y));
}
//------------------------------------
ofVec3f ofxKinect::getWorldCoordinateAt(float cx, float cy, float wz) {
double wx, wy;
freenect_camera_to_world(kinectDevice, cx, cy, wz, &wx, &wy);
return ofVec3f(wx, wy, wz);
}
//------------------------------------
ofColor ofxKinect::getColorAt(int x, int y) {
int index = (y * width + x) * bytespp;
ofColor c;
c.r = videoPixels[index + 0];
c.g = videoPixels[index + (bytespp-1)/2];
c.b = videoPixels[index + (bytespp-1)];
c.a = 255;
return c;
}
//------------------------------------
ofColor ofxKinect::getColorAt(const ofPoint & p) {
return getColorAt(p.x, p.y);
}
//---------------------------------------------------------------------------
ofPoint ofxKinect::getRawAccel() {
return rawAccel;
}
//---------------------------------------------------------------------------
ofPoint ofxKinect::getMksAccel() {
return mksAccel;
}
//---------------------------------------------------------------------------
unsigned char * ofxKinect::getPixels() {
return videoPixels;
}
//---------------------------------------------------------------------------
unsigned char * ofxKinect::getDepthPixels() {
return depthPixels;
}
//---------------------------------------------------------------------------
unsigned short * ofxKinect::getRawDepthPixels() {
return depthPixelsRaw;
}
//---------------------------------------------------------------------------
float* ofxKinect::getDistancePixels() {
return distancePixels;
}
//------------------------------------
ofTexture& ofxKinect::getTextureReference(){
if(!videoTex.bAllocated()){
ofLog(OF_LOG_WARNING, "ofxKinect: getTextureReference - texture is not allocated");
}
return videoTex;
}
//---------------------------------------------------------------------------
ofTexture& ofxKinect::getDepthTextureReference(){
if(!depthTex.bAllocated()){
ofLog(OF_LOG_WARNING, "ofxKinect: getDepthTextureReference - texture is not allocated");
}
return depthTex;
}
//---------------------------------------------------------------------------
ofPixels& ofxKinect::getPixelsRef() {
return pixels;
}
//---------------------------------------------------------------------------
void ofxKinect::enableDepthNearValueWhite(bool bEnabled) {
bNearWhite = bEnabled;
updateDepthLookupTable();
}
//---------------------------------------------------------------------------
bool ofxKinect::isDepthNearValueWhite() {
return bNearWhite;
}
//---------------------------------------------------------------------------
void ofxKinect::setDepthClipping(float nearClip, float farClip) {
nearClipping = nearClip;
farClipping = farClip;
updateDepthLookupTable();
}
//---------------------------------------------------------------------------
float ofxKinect::getNearClipping() {
return nearClipping;
}
//---------------------------------------------------------------------------
float ofxKinect::getFarClipping() {
return farClipping;
}
// we update the value here, but apply it in kinect thread
//--------------------------------------------------------------------
bool ofxKinect::setCameraTiltAngle(float angleInDegrees) {
if(!bGrabberInited) {
return false;
}
targetTiltAngleDeg = ofClamp(angleInDegrees, -30, 30);
bTiltNeedsApplying = true;
return true;
}
//--------------------------------------------------------------------
float ofxKinect::getTargetCameraTiltAngle() {
return targetTiltAngleDeg;
}
float ofxKinect::getCurrentCameraTiltAngle() {
return currentTiltAngleDeg;
}
//------------------------------------
void ofxKinect::setUseTexture(bool bUse){
bUseTexture = bUse;
}
//----------------------------------------------------------
void ofxKinect::draw(float _x, float _y, float _w, float _h) {
if(bUseTexture && bGrabVideo) {
videoTex.draw(_x, _y, _w, _h);
}
}
//----------------------------------------------------------
void ofxKinect::draw(float _x, float _y) {
draw(_x, _y, (float)width, (float)height);
}
//----------------------------------------------------------
void ofxKinect::draw(const ofPoint & point) {
draw(point.x, point.y);
}
//----------------------------------------------------------
void ofxKinect::draw(const ofRectangle & rect) {
draw(rect.x, rect.y, rect.width, rect.height);
}
//----------------------------------------------------------
void ofxKinect::drawDepth(float _x, float _y, float _w, float _h) {
if(bUseTexture) {
depthTex.draw(_x, _y, _w, _h);
}
}
//---------------------------------------------------------------------------
void ofxKinect::drawDepth(float _x, float _y) {
drawDepth(_x, _y, (float)width, (float)height);
}
//----------------------------------------------------------
void ofxKinect::drawDepth(const ofPoint & point) {
drawDepth(point.x, point.y);
}
//----------------------------------------------------------
void ofxKinect::drawDepth(const ofRectangle & rect) {
drawDepth(rect.x, rect.y, rect.width, rect.height);
}
//---------------------------------------------------------------------------
int ofxKinect::getDeviceId() {
return kinectContext.getId(*this);
}
//----------------------------------------------------------
float ofxKinect::getHeight() {
return (float) height;
}
//---------------------------------------------------------------------------
float ofxKinect::getWidth() {
return (float) width;
}
//---------------------------------------------------------------------------
int ofxKinect::numTotalDevices() {
return kinectContext.numTotal();
}
//---------------------------------------------------------------------------
int ofxKinect::numAvailableDevices() {
return kinectContext.numAvailable();
}
//---------------------------------------------------------------------------
int ofxKinect::numConnectedDevices() {
return kinectContext.numConnected();
}
//---------------------------------------------------------------------------
bool ofxKinect::isDeviceConnected(int id) {
return kinectContext.isConnected(id);
}
//---------------------------------------------------------------------------
int ofxKinect::nextAvailableId() {
return kinectContext.nextAvailableId();
}
/* ***** PRIVATE ***** */
//---------------------------------------------------------------------------
void ofxKinect::updateDepthLookupTable() {
unsigned char nearColor = bNearWhite ? 255 : 0;
unsigned char farColor = bNearWhite ? 0 : 255;
unsigned int maxDepthLevels = 10000;
depthLookupTable.resize(maxDepthLevels);
depthLookupTable[0] = 0;
for(int i = 1; i < maxDepthLevels; i++) {
depthLookupTable[i] = ofMap(i, nearClipping, farClipping, nearColor, farColor, true);
}
}
//----------------------------------------------------------
void ofxKinect::updateDepthPixels() {
int n = width * height;
for(int i = 0; i < n; i++) {
distancePixels[i] = depthPixelsRaw[i];
}
for(int i = 0; i < n; i++) {
depthPixels[i] = depthLookupTable[depthPixelsRaw[i]];
}
}
//---------------------------------------------------------------------------
void ofxKinect::grabDepthFrame(freenect_device *dev, void *depth, uint32_t timestamp) {
ofxKinect* kinect = kinectContext.getKinect(dev);
if(kinect->kinectDevice == dev && kinect->lock()) {
try {
freenect_frame_mode curMode = freenect_get_current_depth_mode(dev);
memcpy(kinect->depthPixelsBack, depth, curMode.bytes);
kinect->bNeedsUpdate = true;
}
catch(...) {
ofLog(OF_LOG_ERROR, "ofxKinect: Depth memcpy failed for device %d", kinect->getDeviceId());
}
kinect->unlock();
}
else {
ofLog(OF_LOG_WARNING, "ofxKinect: grabDepthFrame unable to lock mutex");
}
}
//---------------------------------------------------------------------------
void ofxKinect::grabRgbFrame(freenect_device *dev, void *rgb, uint32_t timestamp) {
ofxKinect* kinect = kinectContext.getKinect(dev);
if(kinect->kinectDevice == dev && kinect->lock()) {
try {
freenect_frame_mode curMode = freenect_get_current_video_mode(dev);
memcpy(kinect->videoPixelsBack, rgb, curMode.bytes);
kinect->bNeedsUpdate = true;
}
catch (...) {
ofLog(OF_LOG_ERROR, "ofxKinect: Rgb memcpy failed for device %d",
kinect->getDeviceId());
}
kinect->unlock();
}
else {
ofLog(OF_LOG_ERROR, "ofxKinect: grabRgbFrame unable to lock mutex");
}
}
//---------------------------------------------------------------------------
void ofxKinect::threadedFunction(){
freenect_set_led(kinectDevice, LED_GREEN);
freenect_frame_mode videoMode = freenect_find_video_mode(FREENECT_RESOLUTION_MEDIUM, bInfrared ? FREENECT_VIDEO_IR_8BIT : FREENECT_VIDEO_RGB);
freenect_set_video_mode(kinectDevice, videoMode);
freenect_frame_mode depthMode = freenect_find_depth_mode(FREENECT_RESOLUTION_MEDIUM, bUseRegistration ? FREENECT_DEPTH_REGISTERED : FREENECT_DEPTH_MM);
freenect_set_depth_mode(kinectDevice, depthMode);
ofLog(OF_LOG_VERBOSE, "ofxKinect: Device %d connection opened", kinectContext.getId(*this));
freenect_start_depth(kinectDevice);
if(bGrabVideo) {
freenect_start_video(kinectDevice);
}
// call platform specific processors (needed for Win)
if(freenect_process_events(kinectContext.getContext()) != 0) {
ofLog(OF_LOG_ERROR, "ofxKinect: freenect_process_events failed!");
return;
}
while(isThreadRunning()) {
if(bTiltNeedsApplying) {
freenect_set_tilt_degs(kinectDevice, targetTiltAngleDeg);
bTiltNeedsApplying = false;
}
freenect_update_tilt_state(kinectDevice);
freenect_raw_tilt_state * tilt = freenect_get_tilt_state(kinectDevice);
currentTiltAngleDeg = freenect_get_tilt_degs(tilt);
rawAccel.set(tilt->accelerometer_x, tilt->accelerometer_y, tilt->accelerometer_z);
double dx,dy,dz;
freenect_get_mks_accel(tilt, &dx, &dy, &dz);
mksAccel.set(dx, dy, dz);
// ... and $0.02 for the scheduler
ofSleepMillis(10);
}
// finish up a tilt on exit
if(bTiltNeedsApplying) {
freenect_set_tilt_degs(kinectDevice, targetTiltAngleDeg);
bTiltNeedsApplying = false;
}
freenect_stop_depth(kinectDevice);
freenect_stop_video(kinectDevice);
freenect_set_led(kinectDevice, LED_YELLOW);
int id = kinectContext.getId(*this);
kinectContext.close(*this);
ofLog(OF_LOG_VERBOSE, "ofxKinect: Device %d connection closed", id);
}
//---------------------------------------------------------------------------
// ofxKinectContext
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
ofxKinectContext::ofxKinectContext() {
kinectContext = NULL;
}
ofxKinectContext::~ofxKinectContext() {
closeAll();
clear();
}
//---------------------------------------------------------------------------
bool ofxKinectContext::init() {
if(freenect_init(&kinectContext, NULL) < 0) {
ofLog(OF_LOG_ERROR, "ofxKinect: freenect_init failed");
return false;
}
ofLog(OF_LOG_VERBOSE, "ofxKinect: Context inited");
return true;
}
//---------------------------------------------------------------------------
void ofxKinectContext::clear() {
if(isInited() && numConnected() < 1) {
freenect_shutdown(kinectContext);
kinectContext = NULL;
ofLog(OF_LOG_VERBOSE, "ofxKinect: Context cleared");
}
}
bool ofxKinectContext::isInited() {
return kinectContext != NULL;
}
bool ofxKinectContext::open(ofxKinect& kinect, int id) {
if(numConnected() >= numTotal()) {
ofLog(OF_LOG_WARNING, "ofxKinect Cannot open any more devices");
return false;
}
// is the id available?
if(id < 0) {
id = nextAvailableId();
}
else {
if(isConnected(id)) {
ofLog(OF_LOG_WARNING, "ofxKinect: Device %d already connected", id);
return false;
}
}
// open and add to vector
if(freenect_open_device(kinectContext, &kinect.kinectDevice, id) < 0) {
ofLog(OF_LOG_ERROR, "ofxKinect: Could not open device %d", id);
return false;
}
kinects.insert(pair<int,ofxKinect*>(id, &kinect));
return true;
}
void ofxKinectContext::close(ofxKinect& kinect) {
// already closed?
int id = getId(kinect);
if(id == -1) {
return;
}
// remove connected device and close
std::map<int,ofxKinect*>::iterator iter = kinects.find(id);
if(iter != kinects.end()) {
kinects.erase(iter);
freenect_close_device(kinect.kinectDevice);
}
}
void ofxKinectContext::closeAll() {
std::map<int,ofxKinect*>::iterator iter;
for(iter = kinects.begin(); iter != kinects.end(); ++iter) {
iter->second->close();
}
}
//---------------------------------------------------------------------------
int ofxKinectContext::numTotal() {
if(!isInited())
init();
return freenect_num_devices(kinectContext);
}
int ofxKinectContext::numAvailable() {
if(!isInited())
init();
return freenect_num_devices(kinectContext) - kinects.size();
}
int ofxKinectContext::numConnected() {
return kinects.size();
}
int ofxKinectContext::getId(ofxKinect& kinect) {
std::map<int,ofxKinect*>::iterator iter;
for(iter = kinects.begin(); iter != kinects.end(); ++iter) {
if(iter->second == &kinect)
return iter->first;
}
return -1;
}
ofxKinect* ofxKinectContext::getKinect(freenect_device* dev) {
std::map<int,ofxKinect*>::iterator iter;
for(iter = kinects.begin(); iter != kinects.end(); ++iter) {
if(iter->second->kinectDevice == dev)
return iter->second;
}
return NULL;
}
bool ofxKinectContext::isConnected(int index) {
std::map<int,ofxKinect*>::iterator iter = kinects.find(index);
return iter != kinects.end();
}
int ofxKinectContext::nextAvailableId() {
// a brute force free index finder :D
std::map<int,ofxKinect*>::iterator iter;
for(int i = 0; i < numTotal(); ++i) {
iter = kinects.find(i);
if(iter == kinects.end())
return i;
}
return -1;
}