Source

neverkinect / share / tilt_kinect.c

  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
/*
 * Copyright (C) 2003 Robert Kooima
 * Copyright (C) 2012 Julian Habrock
 *
 * NEVERBALL is  free software; you can redistribute  it and/or modify
 * it under the  terms of the GNU General  Public License as published
 * by the Free  Software Foundation; either version 2  of the License,
 * or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT  ANY  WARRANTY;  without   even  the  implied  warranty  of
 * MERCHANTABILITY or  FITNESS FOR A PARTICULAR PURPOSE.   See the GNU
 * General Public License for more details.
 */

#include <SDL.h>
#include <SDL_thread.h>
#include <math.h>
#include <stdio.h>

#include "config.h"

#include <stdlib.h>



/*---------------------------------------------------------------------------*/

/* FIXME: I *did* copy paste this from tilt_loop.c, I swear! */

/*
 * This data structure tracks button changes, counting transitions so that
 * none are missed if the event handling thread falls significantly behind
 * the device IO thread.
 */

#define BUTTON_NC 0
#define BUTTON_DN 1
#define BUTTON_UP 2

struct button_state
{
    unsigned char curr;
    unsigned char last;
    unsigned char upc;
    unsigned char dnc;
};

static void set_button(struct button_state *B, int s)
{
    if ((B->curr == 0) != (s == 0))
    {
        if (B->curr)
        {
            B->upc++;
            B->curr = 0;
        }
        else
        {
            B->dnc++;
            B->curr = 1;
        }
    }
}

static int get_button(struct button_state *B)
{
    int ch = BUTTON_NC;

    if      (B->last == 1 && B->upc > 0)
    {
        B->upc--;
        B->last = 0;
        ch = BUTTON_UP;
    }
    else if (B->last == 0 && B->dnc > 0)
    {
        B->dnc--;
        B->last = 1;
        ch = BUTTON_DN;
    }

    return ch;
}

/*---------------------------------------------------------------------------*/

struct tilt_state
{
    int   status;
    float x;
    float z;
    struct button_state A;
    struct button_state B;
    struct button_state plus;
    struct button_state minus;
    struct button_state home;
    struct button_state L;
    struct button_state R;
    struct button_state U;
    struct button_state D;
};

static struct tilt_state state;
static SDL_mutex        *mutex  = NULL;
static SDL_Thread       *thread = NULL;

/*---------------------------------------------------------------------------*/

/* kinect / OpenNI part */


#include <XnOpenNI.h>



// openni variables


static XnContext *pContext;
static XnNodeHandle hDepth;
static XnDepthMetaData *pDepthMD;
static XnNodeHandle hUserGenerator;

static XnChar g_strPose[20] = "";

// caches all joint coords
static float allJointCoords[24][3];



//  New user
void XN_CALLBACK_TYPE new_user(XnNodeHandle generator,
			       XnUserID nId, 
			       void* pCookie) {
	printf("New User %d\n", nId);

	xnRequestSkeletonCalibration(generator, nId, TRUE);
}

// user lost
void XN_CALLBACK_TYPE lost_user(XnNodeHandle generator,
				XnUserID nId, 
				void* pCookie) {
	printf("Lost user %d\n", nId);
	
}


// Callback: Detected a pose
void XN_CALLBACK_TYPE pose_detected(XnNodeHandle capability, const XnChar* strPose, XnUserID nId, void* pCookie) {
	printf("Pose %s detected for user %d\n", strPose, nId);
	
	xnStopPoseDetection(capability, nId);
	xnRequestSkeletonCalibration(capability, nId, TRUE);
}


// Callback: Started calibration
void XN_CALLBACK_TYPE calibration_started(XnNodeHandle capability, XnUserID nId, void* pCookie) {
	printf("Calibration started for user %d\n", nId);
}



// Callback: Finished calibration
void XN_CALLBACK_TYPE calibration_ended(XnNodeHandle capability, XnUserID nId, XnCalibrationStatus status, void* pCookie) {
	if (status != XN_CALIBRATION_STATUS_NO_USER) {
		printf("Calibration complete, start tracking user %d\n", nId);
		xnStartSkeletonTracking(capability, nId);
	}
	else {
		printf("Calibration failed for user %d\n", nId);
		xnRequestSkeletonCalibration(capability, nId, TRUE);
	}
}



int jointPos(XnUserID player, XnSkeletonJoint eJoint) {
        
	XnSkeletonJointTransformation jointTrans;

	//userGenerator.GetSkeletonCap().GetSkeletonJoint(player, eJoint, jointTrans);
	xnGetSkeletonJoint(hUserGenerator, player, eJoint, &jointTrans);


	//if (jointTrans.position.fConfidence < 0.5) {
	//	return 0;
	//}

	XnPoint3D realwordPoint;
	realwordPoint.X = 0; realwordPoint.Y = 0; realwordPoint.Z = 0;
	
	//depth.ConvertProjectiveToRealWorld(1, &jointTrans.position.position, &realwordPoint); 
	xnConvertProjectiveToRealWorld(hDepth, 1, &jointTrans.position.position, &realwordPoint); 
	
	allJointCoords[eJoint-1][0] = realwordPoint.X;
	allJointCoords[eJoint-1][1] = realwordPoint.Y;
	allJointCoords[eJoint-1][2] = realwordPoint.Z;
	
	return 0;
}


void get_body_positions(){
  
        int userCount = xnGetNumberOfUsers(hUserGenerator);
	XnUserID *aUsers = malloc(userCount*sizeof(XnUserID));
	XnUInt16 nUsers = userCount * sizeof(XnUserID);
	for(int i = 0;i<userCount;i++){
	  aUsers[i] = 0;
	}
	xnGetUsers(hUserGenerator, aUsers, &nUsers);
	if (nUsers > 0){
		//if (userGenerator.GetSkeletonCap().IsTracking(aUsers[0])) {
		 if (xnIsSkeletonTracking(hUserGenerator,aUsers[0])){
		  printf("is skeleton tracking");
		  for(int j=1;j<25;j++){
		    jointPos(aUsers[0], (XnSkeletonJoint) j);
		  }		
		}
	}
	free(aUsers);
}

void checkRetVal(XnStatus nRetVal) {
	if (nRetVal != XN_STATUS_OK) {
		printf("There was a problem initializing kinect... Make sure you have \
connected both usb and power cables and that the driver and OpenNI framework \
are correctly installed.\n\n");
		printf("Error was: %s\n", xnGetStatusString(nRetVal));
		exit(1);
	}
}

void main_loop() {
	// Read next available data
	//context.WaitAnyUpdateAll();
	xnWaitAnyUpdateAll(pContext);
	
	// Process the data
	//depth.GetMetaData(depthMD);
	xnGetDepthMetaData(hDepth, pDepthMD);
	
	get_body_positions();
}


void init_kinect() {
	printf("Initializing...\n");
	
	XnStatus nRetVal = XN_STATUS_OK;
	XnCallbackHandle hUserCallbacks, hCalibrationCallbacks, hPoseCallbacks;


	//context.Init();
	xnInit(&pContext);
	
	pDepthMD = xnAllocateDepthMetaData();


	//depth.Create(context);
	
	nRetVal = xnCreateDepthGenerator(pContext, &hDepth, NULL, NULL);//&errors);
	// TODO: error handling
	if (nRetVal != (XnStatus)0){
	  printf("error at depth generator create!");
	}
	
	if (nRetVal == XN_STATUS_NO_NODE_PRESENT)
	{
	
	}
	else if (nRetVal != XN_STATUS_OK)
	{
	    printf("Create failed: %s\n", xnGetStatusString(nRetVal));
	}


	nRetVal = xnCreateUserGenerator(pContext, &hUserGenerator, NULL, NULL);

	if (nRetVal != (XnStatus)0){
	   printf("error at user generator create!");
	}


	//checkRetVal(userGenerator.RegisterUserCallbacks(new_user, lost_user, NULL, hUserCallbacks));
	//checkRetVal(userGenerator.GetSkeletonCap().RegisterCalibrationCallbacks(calibration_started, calibration_ended, NULL, hCalibrationCallbacks));
	//checkRetVal(userGenerator.GetPoseDetectionCap().RegisterToPoseCallbacks(pose_detected, NULL, NULL, hPoseCallbacks));
	//checkRetVal(userGenerator.GetSkeletonCap().GetCalibrationPose(g_strPose));
	//checkRetVal(userGenerator.GetSkeletonCap().SetSkeletonProfile(XN_SKEL_PROFILE_ALL));
	
	checkRetVal(xnRegisterUserCallbacks(hUserGenerator, &new_user, &lost_user, NULL, &hUserCallbacks));
	checkRetVal(xnRegisterToCalibrationStart(hUserGenerator, &calibration_started, NULL, &hCalibrationCallbacks));
	checkRetVal(xnRegisterToCalibrationComplete(hUserGenerator, &calibration_ended, NULL, &hCalibrationCallbacks));		
	checkRetVal(xnRegisterToPoseDetected(hUserGenerator, &pose_detected, NULL, &hPoseCallbacks));
	checkRetVal(xnGetSkeletonCalibrationPose(hUserGenerator, g_strPose));
	checkRetVal(xnSetSkeletonProfile(hUserGenerator, XN_SKEL_PROFILE_ALL));
	
	printf("Initialized Kinect, looking for users...\n\n");
	
	//context.StartGeneratingAll();	
	xnStartGeneratingAll(pContext);

	
}


void free_kinect(){
  //xnFreeDepthMetaData(pDepthMD);
  xnContextRelease(pContext);
}

static int tilt_func(void *data)
{
       printf("hello kinect world! inited!");
       
    int running = 1;

    SDL_mutexP(mutex);
    state.status = running;
    SDL_mutexV(mutex);

    while (mutex && running)
    {
        SDL_mutexP(mutex);
        running = state.status;
        SDL_mutexV(mutex);

	    main_loop();
	    	    
            SDL_mutexP(mutex);
            {
             float deltaX, deltaZ;
  
	      // difference in mm from neck to waist
	      deltaX = (allJointCoords[XN_SKEL_NECK-1][0] - allJointCoords[XN_SKEL_WAIST-1][0]) / 20;//200;
	      deltaZ = (allJointCoords[XN_SKEL_NECK-1][2] - allJointCoords[XN_SKEL_WAIST-1][2] - 10) / 5;//100;
	      
	   /*  if (deltaX > 1) deltaX = 1;
	      else if (deltaX < -1) deltaX = -1;
	      if (deltaZ > 1) deltaZ = 1;
	      else if (deltaZ < -1) deltaZ = -1;*/
	      
	      int button = 0;
	      
	      if (allJointCoords[XN_SKEL_RIGHT_HAND][1] < allJointCoords[XN_SKEL_HEAD][1]){  // small y -> high object, ie if hand.y < head.y -> hand is above head
		button = 1;
		printf("button: 1!");
	      }else if (allJointCoords[XN_SKEL_LEFT_HAND][1] < allJointCoords[XN_SKEL_HEAD][1]){
		button = 2;
		printf("button: 2!");
	      }
	      
                state.x = -deltaZ;
                state.z = -deltaX;
		
		set_button(&state.minus, button == 1);
		set_button(&state.plus, button == 2);		
            }
            SDL_mutexV(mutex);
    }

    free_kinect();
    return 0;
}



void tilt_init(void)
{
    memset(&state, 0, sizeof (struct tilt_state));

    init_kinect();

    mutex  = SDL_CreateMutex();
    thread = SDL_CreateThread(tilt_func, NULL);
}

void tilt_free(void)
{
    int b = 0;

    if (mutex)
    {
        /* Get/set the status of the tilt sensor thread. */

        SDL_mutexP(mutex);
        b = state.status;
        state.status = 0;
        SDL_mutexV(mutex);

        /* Kill the thread and destroy the mutex. */

        SDL_WaitThread(thread, &b);
        SDL_DestroyMutex(mutex);

        mutex  = NULL;
        thread = NULL;

	free_kinect();
    }
}

int tilt_get_button(int *b, int *s)
{
    int ch = BUTTON_NC;

    if (mutex)
    {
        SDL_mutexP(mutex);
        {
            if      ((ch = get_button(&state.A)))
            {
                *b = config_get_d(CONFIG_JOYSTICK_BUTTON_A);
                *s = (ch == BUTTON_DN);
            }
            else if ((ch = get_button(&state.B)))
            {
                *b = config_get_d(CONFIG_JOYSTICK_BUTTON_B);
                *s = (ch == BUTTON_DN);
            }
            else if ((ch = get_button(&state.home)))
            {
                *b = config_get_d(CONFIG_JOYSTICK_BUTTON_EXIT);
                *s = (ch == BUTTON_DN);
            }
            else if ((ch = get_button(&state.U)))
            {
                *b = config_get_d(CONFIG_JOYSTICK_DPAD_U);
                *s = (ch == BUTTON_DN);
            }
            else if ((ch = get_button(&state.D)))
            {
                *b = config_get_d(CONFIG_JOYSTICK_DPAD_D);
                *s = (ch == BUTTON_DN);
            }
            else if ((ch = get_button(&state.plus)))
            {
                *b = config_get_d(CONFIG_JOYSTICK_BUTTON_R);
                *s = (ch == BUTTON_DN);
            }
            else if ((ch = get_button(&state.minus)))
            {
                *b = config_get_d(CONFIG_JOYSTICK_BUTTON_L);
                *s = (ch == BUTTON_DN);
            }
        }
        SDL_mutexV(mutex);
    }
    return ch;
}

float tilt_get_x(void)
{
    float x = 0.0f;

    if (mutex)
    {
        SDL_mutexP(mutex);
        x = state.x;
        SDL_mutexV(mutex);
    }

    return x;
}

float tilt_get_z(void)
{
    float z = 0.0f;

    if (mutex)
    {
        SDL_mutexP(mutex);
        z = state.z;
        SDL_mutexV(mutex);
    }

    return z;
}

int tilt_stat(void)
{
    int b = 0;

    if (mutex)
    {
        SDL_mutexP(mutex);
        b = state.status;
        SDL_mutexV(mutex);
    }
    return b;
}

/*---------------------------------------------------------------------------*/