-
Notifications
You must be signed in to change notification settings - Fork 0
/
BodyBasics.cpp
1581 lines (1406 loc) · 46.2 KB
/
BodyBasics.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
//------------------------------------------------------------------------------
// <copyright file="BodyBasics.cpp" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
#include "stdafx.h"
#include <strsafe.h>
#include "resource.h"
#include "BodyBasics.h"
#include <math.h>
#include "filter.h"
#include <process.h>
#include <stdlib.h>
#include <Shellapi.h>
static const float c_JointThickness = 3.0f;
static const float c_TrackedBoneThickness = 6.0f;
static const float c_InferredBoneThickness = 1.0f;
static const float c_HandSize = 30.0f;
vector<Action> actionlist;
int actionNum = 0;
bool sendinput = false;
bool drawnewtemp = false;
bool drawstarted = false;
bool showtemp = false;
bool record = false;
bool recording = false;
string nowconfig = "";
HACCEL hAccel;
wstring nowtemplate = L"";
bool loadtemplate(int num, string filename)
{
fstream in(filename);
if (in.fail())
{
return false;
}
vector<VEC> v;
VEC t;
while (in >> t)
{
v.push_back(t);
}
v = normalize(v);
templates.push_back(v);
return true;
}
void loadConfig(wstring filename, wstring path)
{
templates.clear();
actionlist.clear();
string spath(path.begin(), path.end());
fstream config(filename, ios::in);
if (config.fail())
{
MessageBoxA(NULL, "No such config file exist!", "Error", MB_OK);
}
while (true)
{
string command = "";
string tempname = "";
string action = "";
config >> command;
if (config.eof()) break;
if (strcmpi(command.c_str(), "TEMPLATE") == 0)
{
config >> tempname;
tempname = spath + tempname;
if (config.eof()) break;
if (!loadtemplate(actionNum, tempname))
{
string msg = "Template file " + tempname + " not exist!";
MessageBoxA(NULL, msg.c_str(), "Error!", MB_OK);
templates.clear();
actionlist.clear();
return;
}
config >> command;
if (config.eof()) break;
Action newaction;
if (strcmpi(command.c_str(), "ACTION") == 0)
{
getline(config, action);
newaction.type = Action::Command;
newaction.action = action;
}
else if (strcmpi(command.c_str(), "MOUSE") == 0)
{
config >> command;
if (strcmpi(command.c_str(), "WHEEL") == 0)
{
newaction.mouse = MOUSEEVENTF_WHEEL;
newaction.wheelamount = 0;
config >> newaction.wheelamount;
}
else if (strcmpi(command.c_str(), "RCLK") == 0)
{
newaction.mouse = MOUSEEVENTF_RIGHTDOWN | MOUSEEVENTF_RIGHTUP;
}
else
{
MessageBoxA(NULL, "Unrecognized command!", "Error", MB_OK);
templates.clear();
actionlist.clear();
}
newaction.type = Action::Mouse;
}
else if (strcmpi(command.c_str(), "VK") == 0)
{
config >> newaction.vk;
newaction.type = Action::Key_VK;
}
actionNum++;
actionlist.push_back(newaction);
}
}
}
/// <summary>
/// Entry point for the application
/// </summary>
/// <param name="hInstance">handle to the application instance</param>
/// <param name="hPrevInstance">always 0</param>
/// <param name="lpCmdLine">command line arguments</param>
/// <param name="nCmdShow">whether to display minimized, maximized, or normally</param>
/// <returns>status</returns>
int APIENTRY wWinMain(
_In_ HINSTANCE hInstance,
_In_opt_ HINSTANCE hPrevInstance,
_In_ LPWSTR lpCmdLine,
_In_ int nShowCmd
)
{
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
CBodyBasics application;
application.Run(hInstance, nShowCmd);
}
/// <summary>
/// Constructor
/// </summary>
CBodyBasics::CBodyBasics() :
m_hWnd(NULL),
m_nStartTime(0),
m_nLastCounter(0),
m_nFramesSinceUpdate(0),
m_fFreq(0),
m_nNextStatusTime(0LL),
m_pKinectSensor(NULL),
m_pCoordinateMapper(NULL),
m_pBodyFrameReader(NULL),
m_pD2DFactory(NULL),
m_pTempFactory(NULL),
m_pRenderTarget(NULL),
m_pTempRenderTarget(NULL),
m_pBrushJointTracked(NULL),
m_pBrushJointInferred(NULL),
m_pBrushBoneTracked(NULL),
m_pBrushBoneInferred(NULL),
m_pBrushHandClosed(NULL),
m_pBrushHandOpen(NULL),
m_pBrushHandLasso(NULL),
p2draw(0)
{
LARGE_INTEGER qpf = {0};
if (QueryPerformanceFrequency(&qpf))
{
m_fFreq = double(qpf.QuadPart);
}
ZeroMemory(&ljx_m_sLeft, sizeof(ljx_m_sLeft));
ljx_m_sLeft.State = HandState_NotTracked;
ljx_m_sLeft.StateLast = HandState_NotTracked;
ZeroMemory(&ljx_m_sRight, sizeof(ljx_m_sRight));
ljx_m_sRight.State = HandState_NotTracked;
ljx_m_sRight.StateLast = HandState_NotTracked;
ljx_m_bRecording = false;
}
/// <summary>
/// Destructor
/// </summary>
CBodyBasics::~CBodyBasics()
{
DiscardDirect2DResources();
// clean up Direct2D
SafeRelease(m_pD2DFactory);
SafeRelease(m_pTempFactory);
// done with body frame reader
SafeRelease(m_pBodyFrameReader);
// done with coordinate mapper
SafeRelease(m_pCoordinateMapper);
// close the Kinect Sensor
if (m_pKinectSensor)
{
m_pKinectSensor->Close();
}
SafeRelease(m_pKinectSensor);
}
/// <summary>
/// Creates the main window and begins processing
/// </summary>
/// <param name="hInstance">handle to the application instance</param>
/// <param name="nCmdShow">whether to display minimized, maximized, or normally</param>
int CBodyBasics::Run(HINSTANCE hInstance, int nCmdShow)
{
MSG msg = {0};
WNDCLASS wc;
int argc;
LPWSTR *arglist;
// Dialog custom window class
ZeroMemory(&wc, sizeof(wc));
wc.style = CS_HREDRAW | CS_VREDRAW;
wc.cbWndExtra = DLGWINDOWEXTRA;
wc.hCursor = LoadCursorW(NULL, IDC_ARROW);
wc.hIcon = LoadIconW(hInstance, MAKEINTRESOURCE(IDI_APP));
wc.lpfnWndProc = DefDlgProcW;
wc.lpszClassName = L"BodyBasicsAppDlgWndClass";
if (!RegisterClassW(&wc))
{
return 0;
}
// Create main application window
HWND hWndApp = CreateDialogParamW(
NULL,
MAKEINTRESOURCE(IDD_APP),
NULL,
(DLGPROC)CBodyBasics::MessageRouter,
reinterpret_cast<LPARAM>(this));
// Show window
ShowWindow(hWndApp, nCmdShow);
hAccel = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDR_ACCELERATOR1));
arglist = CommandLineToArgvW(GetCommandLine(), &argc);
if (argc >= 1)
{
for (int i = 1; i < __argc; i++)
{
wstring cmd(arglist[i]);
if (cmd == L"-input")
{
sendinput = true;
}
else if (cmd == L"-config")
{
wstring filename;
if (i + 1 <= argc)
{
filename = arglist[i + 1];
i++;
int pos = filename.length();
while (filename[pos] != wchar_t('\\')) pos--;
wstring fileparent(L"");
for (int l = 0; l <= pos; l++)
{
fileparent = fileparent + filename[l];
}
loadConfig(filename, fileparent);
}
else
{
MessageBoxA(NULL, "No config file specified!", "Error", MB_OK);
exit(0);
}
}
else
{
MessageBox(NULL, (wstring(L"Unknown parameter : ") + cmd).c_str(), L"Error", MB_OK);
}
}
}
// Main message loop
while (WM_QUIT != msg.message)
{
Update();
while (PeekMessageW(&msg, NULL, 0, 0, PM_REMOVE))
{
// If a dialog message will be taken care of by the dialog proc
if (hWndApp && IsDialogMessageW(hWndApp, &msg))
{
continue;
}
if (!TranslateAccelerator(m_hWnd, hAccel, &msg))
{
TranslateMessage(&msg);
DispatchMessageW(&msg);
}
}
}
return static_cast<int>(msg.wParam);
}
/// <summary>
/// Main processing function
/// </summary>
void CBodyBasics::Update()
{
if (!m_pBodyFrameReader)
{
return;
}
IBodyFrame* pBodyFrame = NULL;
HRESULT hr = m_pBodyFrameReader->AcquireLatestFrame(&pBodyFrame);
if (SUCCEEDED(hr))
{
INT64 nTime = 0;
hr = pBodyFrame->get_RelativeTime(&nTime);
IBody* ppBodies[BODY_COUNT] = {0};
if (SUCCEEDED(hr))
{
hr = pBodyFrame->GetAndRefreshBodyData(_countof(ppBodies), ppBodies);
}
if (SUCCEEDED(hr))
{
ProcessBody(nTime, BODY_COUNT, ppBodies);
}
for (int i = 0; i < _countof(ppBodies); ++i)
{
SafeRelease(ppBodies[i]);
}
}
SafeRelease(pBodyFrame);
}
/// <summary>
/// Handles window messages, passes most to the class instance to handle
/// </summary>
/// <param name="hWnd">window message is for</param>
/// <param name="uMsg">message</param>
/// <param name="wParam">message data</param>
/// <param name="lParam">additional message data</param>
/// <returns>result of message processing</returns>
LRESULT CALLBACK CBodyBasics::MessageRouter(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
CBodyBasics* pThis = NULL;
if (WM_INITDIALOG == uMsg)
{
pThis = reinterpret_cast<CBodyBasics*>(lParam);
SetWindowLongPtr(hWnd, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(pThis));
}
else
{
pThis = reinterpret_cast<CBodyBasics*>(::GetWindowLongPtr(hWnd, GWLP_USERDATA));
}
if (pThis)
{
return pThis->DlgProc(hWnd, uMsg, wParam, lParam);
}
return 0;
}
/// <summary>
/// Handle windows messages for the class instance
/// </summary>
/// <param name="hWnd">window message is for</param>
/// <param name="uMsg">message</param>
/// <param name="wParam">message data</param>
/// <param name="lParam">additional message data</param>
/// <returns>result of message processing</returns>
LRESULT CALLBACK CBodyBasics::DlgProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
UNREFERENCED_PARAMETER(wParam);
UNREFERENCED_PARAMETER(lParam);
switch (message)
{
case WM_INITDIALOG:
{
// Bind application window handle
m_hWnd = hWnd;
// Init Direct2D
D2D1CreateFactory(D2D1_FACTORY_TYPE_SINGLE_THREADED, &m_pD2DFactory);
D2D1CreateFactory(D2D1_FACTORY_TYPE_SINGLE_THREADED, &m_pTempFactory);
// Get and initialize the default Kinect sensor
InitializeDefaultSensor();
}
break;
// If the titlebar X is clicked, destroy app
case WM_CLOSE:
DestroyWindow(hWnd);
break;
case WM_DESTROY:
// Quit the main message pump
PostQuitMessage(0);
break;
case WM_COMMAND:
if (drawnewtemp)
{
if (drawstarted)
{
drawstarted = false;
ljxEndDrawTemp();
}
drawnewtemp = false;
}
switch (LOWORD(wParam))
{
case IDC_RECORD:
{
if (!record)
{
SetWindowText(GetDlgItem(m_hWnd, IDC_RECORD), L"Disable Record");
record = true;
recording = false;
}
else
{
if (recording)
{
ljxEndRecording();
}
SetWindowText(GetDlgItem(m_hWnd, IDC_RECORD), L"Enable Record");
record = false;
recording = false;
}
break;
}
case IDC_CONFIG:
{
IFileDialog *pfd;
HRESULT hr = CoCreateInstance(CLSID_FileOpenDialog, NULL, CLSCTX_INPROC_SERVER,
IID_PPV_ARGS(&pfd));
DWORD dwFlags;
hr = pfd->GetOptions(&dwFlags);
hr = pfd->SetOptions(dwFlags | FOS_FORCEFILESYSTEM);
COMDLG_FILTERSPEC filter[] = {
{ L"Config File", L"*.txt" },
{ L"All File", L"*.*" }
};
hr = pfd->SetFileTypes(2, filter);
hr = pfd->SetFileTypeIndex(1);
hr = pfd->Show(m_hWnd);
if (hr == S_OK)
{
IShellItem *result;
hr = pfd->GetResult(&result);
LPWSTR filePath;
hr = result->GetDisplayName(SIGDN_DESKTOPABSOLUTEPARSING, &filePath);
int pos = lstrlen(filePath);
while (filePath[pos] != wchar_t('\\')) pos--;
wstring fileparent(L"");
for (int i = 0; i <= pos; i++)
{
fileparent = fileparent + filePath[i];
}
loadConfig(wstring(filePath), fileparent);
}
break;
}
case IDC_CHANGE:
sendinput = !sendinput;
break;
case IDC_TEMPLATE:
{
if (showtemp)
{
SetWindowText(GetDlgItem(m_hWnd, IDC_TEMPLATE), L"Open Template");
showtemp = false;
ljx_m_vTempShowing.clear();
break;
}
IFileDialog *pfd;
HRESULT hr = CoCreateInstance(CLSID_FileOpenDialog, NULL, CLSCTX_INPROC_SERVER,
IID_PPV_ARGS(&pfd));
DWORD dwFlags;
hr = pfd->GetOptions(&dwFlags);
hr = pfd->SetOptions(dwFlags | FOS_FORCEFILESYSTEM);
COMDLG_FILTERSPEC filter[] = {
{ L"All File", L"*.*" }
};
hr = pfd->SetFileTypes(1, filter);
hr = pfd->SetFileTypeIndex(1);
hr = pfd->Show(m_hWnd);
if (hr == S_OK)
{
IShellItem *result;
hr = pfd->GetResult(&result);
LPWSTR fileName;
LPWSTR filePath;
hr = result->GetDisplayName(SIGDN_NORMALDISPLAY, &fileName);
hr = result->GetDisplayName(SIGDN_DESKTOPABSOLUTEPARSING, &filePath);
fstream temp(filePath, ios::in);
ljx_m_vTempShowing.clear();
if (!temp)
{
MessageBoxA(NULL, "No such file!", "Error", MB_OK);
}
VEC t;
while (temp >> t) ljx_m_vTempShowing.push_back(t);
showtemp = true;
SetWindowText(GetDlgItem(m_hWnd, IDC_TEMPLATE), L"Close Template");
}
break;
}
case IDC_NEWTEMP:
showtemp = false;
SetWindowText(GetDlgItem(m_hWnd, IDC_TEMPLATE), L"Open Template");
ljx_m_vTempShowing.clear();
drawnewtemp = true;
break;
}
break;
case WM_LBUTTONDOWN:
{
if (!drawnewtemp)
{
break;
}
RECT rct;
GetWindowRect(GetDlgItem(m_hWnd, IDC_TEMPVIEW), &rct);
POINT lefttop;
lefttop.x = rct.left; lefttop.y = rct.top;
ScreenToClient(m_hWnd, &lefttop);
POINT rightbottom;
rightbottom.x = rct.right; rightbottom.y = rct.bottom;
ScreenToClient(m_hWnd, &rightbottom);
int x, y;
x = LOWORD(lParam);
y = HIWORD(lParam);
if (x >= lefttop.x && x <= rightbottom.x && y >= lefttop.y && y <= rightbottom.y)
{
ljxStartDrawTemp();
drawstarted = true;
}
break;
}
case WM_MOUSEMOVE:
{
if (!drawnewtemp)
{
break;
}
RECT rct;
GetWindowRect(GetDlgItem(m_hWnd, IDC_TEMPVIEW), &rct);
POINT lefttop;
lefttop.x = rct.left; lefttop.y = rct.top;
ScreenToClient(m_hWnd, &lefttop);
POINT rightbottom;
rightbottom.x = rct.right; rightbottom.y = rct.bottom;
ScreenToClient(m_hWnd, &rightbottom);
int x, y;
x = LOWORD(lParam);
y = HIWORD(lParam);
if (x >= lefttop.x && x <= rightbottom.x && y >= lefttop.y && y <= rightbottom.y && drawstarted)
{
x -= lefttop.x; y -= lefttop.y;
int width = rightbottom.x - lefttop.x;
int height = rightbottom.y - lefttop.y;
ljxDrawTemplate(x, y, width, height);
}
break;
}
case WM_LBUTTONUP:
{
if (drawnewtemp)
{
drawstarted = false;
ljxEndDrawTemp();
}
drawnewtemp = false;
break;
}
}
return FALSE;
}
/// <summary>
/// Initializes the default Kinect sensor
/// </summary>
/// <returns>indicates success or failure</returns>
HRESULT CBodyBasics::InitializeDefaultSensor()
{
HRESULT hr;
hr = GetDefaultKinectSensor(&m_pKinectSensor);
if (FAILED(hr))
{
return hr;
}
if (m_pKinectSensor)
{
// Initialize the Kinect and get coordinate mapper and the body reader
IBodyFrameSource* pBodyFrameSource = NULL;
hr = m_pKinectSensor->Open();
if (SUCCEEDED(hr))
{
hr = m_pKinectSensor->get_CoordinateMapper(&m_pCoordinateMapper);
}
if (SUCCEEDED(hr))
{
hr = m_pKinectSensor->get_BodyFrameSource(&pBodyFrameSource);
}
if (SUCCEEDED(hr))
{
hr = pBodyFrameSource->OpenReader(&m_pBodyFrameReader);
}
SafeRelease(pBodyFrameSource);
}
if (!m_pKinectSensor || FAILED(hr))
{
SetStatusMessage(L"No ready Kinect found!", 10000, true);
return E_FAIL;
}
return hr;
}
/// <summary>
/// Handle new body data
/// <param name="nTime">timestamp of frame</param>
/// <param name="nBodyCount">body data count</param>
/// <param name="ppBodies">body data in frame</param>
/// </summary>
void CBodyBasics::ProcessBody(INT64 nTime, int nBodyCount, IBody** ppBodies)
{
if (m_hWnd)
{
HRESULT hr = EnsureDirect2DResources();
if (SUCCEEDED(hr) && m_pRenderTarget && m_pCoordinateMapper)
{
ljxShowJoint();
ljxShowTemplate();
m_pRenderTarget->BeginDraw();
m_pRenderTarget->Clear();
RECT rct, PointRect;
GetClientRect(GetDlgItem(m_hWnd, IDC_VIDEOVIEW), &rct);
int width = rct.right;
int height = rct.bottom;
int mintracted = 9999999;
for (int i = 0; i < nBodyCount; ++i)
{
IBody* pBody = ppBodies[i];
if (pBody)
{
BOOLEAN bTracked = false;
hr = pBody->get_IsTracked(&bTracked);
if (SUCCEEDED(hr) && bTracked && i<=mintracted)
{
mintracted = i;
Joint joints[JointType_Count];
D2D1_POINT_2F jointPoints[JointType_Count];
HandState leftHandState = HandState_Unknown;
HandState rightHandState = HandState_Unknown;
pBody->get_HandLeftState(&leftHandState);
pBody->get_HandRightState(&rightHandState);
hr = pBody->GetJoints(_countof(joints), joints);
if (SUCCEEDED(hr))
{
for (int j = 0; j < _countof(joints); ++j)
{
jointPoints[j] = BodyToScreen(joints[j].Position, width, height);
}
//将得到的数据传递给识别模块
ljxProcessGesture(joints, leftHandState, rightHandState);
DrawBody(joints, jointPoints);
DrawHand(leftHandState, jointPoints[JointType_HandLeft]);
DrawHand(rightHandState, jointPoints[JointType_HandRight]);
}
}
}
}
hr = m_pRenderTarget->EndDraw();
// Device lost, need to recreate the render target
// We'll dispose it now and retry drawing
if (D2DERR_RECREATE_TARGET == hr)
{
hr = S_OK;
DiscardDirect2DResources();
}
}
if (!m_nStartTime)
{
m_nStartTime = nTime;
}
double fps = 0.0;
LARGE_INTEGER qpcNow = {0};
if (m_fFreq)
{
if (QueryPerformanceCounter(&qpcNow))
{
if (m_nLastCounter)
{
m_nFramesSinceUpdate++;
fps = m_fFreq * m_nFramesSinceUpdate / double(qpcNow.QuadPart - m_nLastCounter);
}
}
}
WCHAR szStatusMessage[255];
StringCchPrintf(szStatusMessage, _countof(szStatusMessage), L" FPS = %0.2f Time = %I64d %s %s %s",
fps, (nTime - m_nStartTime), (sendinput) ?L"Inputing" : L"Not Inputing",
(ljx_m_bRecording)?L"Recognizing" : L"Not Recognizing",
(recording)?L"Recording":L"Not Recording");
if (SetStatusMessage(szStatusMessage, 1000, false))
{
m_nLastCounter = qpcNow.QuadPart;
m_nFramesSinceUpdate = 0;
}
}
}
/// <summary>
/// Set the status bar message
/// </summary>
/// <param name="szMessage">message to display</param>
/// <param name="showTimeMsec">time in milliseconds to ignore future status messages</param>
/// <param name="bForce">force status update</param>
bool CBodyBasics::SetStatusMessage(_In_z_ WCHAR* szMessage, DWORD nShowTimeMsec, bool bForce)
{
INT64 now = GetTickCount64();
if (m_hWnd && (bForce || (m_nNextStatusTime <= now)))
{
SetDlgItemText(m_hWnd, IDC_STATUS, szMessage);
m_nNextStatusTime = now + nShowTimeMsec;
return true;
}
return false;
}
/// <summary>
/// Ensure necessary Direct2d resources are created
/// </summary>
/// <returns>S_OK if successful, otherwise an error code</returns>
HRESULT CBodyBasics::EnsureDirect2DResources()
{
HRESULT hr = S_OK;
if (m_pD2DFactory && !m_pRenderTarget)
{
RECT rc;
GetWindowRect(GetDlgItem(m_hWnd, IDC_VIDEOVIEW), &rc);
int width = rc.right - rc.left;
int height = rc.bottom - rc.top;
D2D1_SIZE_U size = D2D1::SizeU(width, height);
D2D1_RENDER_TARGET_PROPERTIES rtProps = D2D1::RenderTargetProperties();
rtProps.pixelFormat = D2D1::PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_IGNORE);
rtProps.usage = D2D1_RENDER_TARGET_USAGE_GDI_COMPATIBLE;
// Create a Hwnd render target, in order to render to the window set in initialize
hr = m_pD2DFactory->CreateHwndRenderTarget(
rtProps,
D2D1::HwndRenderTargetProperties(GetDlgItem(m_hWnd, IDC_VIDEOVIEW), size),
&m_pRenderTarget
);
if (FAILED(hr))
{
SetStatusMessage(L"Couldn't create Direct2D render target!", 10000, true);
return hr;
}
// light green
m_pRenderTarget->CreateSolidColorBrush(D2D1::ColorF(0.27f, 0.75f, 0.27f), &m_pBrushJointTracked);
m_pRenderTarget->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Yellow, 1.0f), &m_pBrushJointInferred);
m_pRenderTarget->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Green, 1.0f), &m_pBrushBoneTracked);
m_pRenderTarget->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Gray, 1.0f), &m_pBrushBoneInferred);
m_pRenderTarget->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Red, 0.5f), &m_pBrushHandClosed);
m_pRenderTarget->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Green, 0.5f), &m_pBrushHandOpen);
m_pRenderTarget->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Blue, 0.5f), &m_pBrushHandLasso);
ljxInitialize();
}
return hr;
}
/// <summary>
/// Dispose Direct2d resources
/// </summary>
void CBodyBasics::DiscardDirect2DResources()
{
SafeRelease(m_pRenderTarget);
SafeRelease(m_pTempRenderTarget);
SafeRelease(m_pBrushJointTracked);
SafeRelease(m_pBrushJointInferred);
SafeRelease(m_pBrushBoneTracked);
SafeRelease(m_pBrushBoneInferred);
SafeRelease(m_pBrushHandClosed);
SafeRelease(m_pBrushHandOpen);
SafeRelease(m_pBrushHandLasso);
}
/// <summary>
/// Converts a body point to screen space
/// </summary>
/// <param name="bodyPoint">body point to tranform</param>
/// <param name="width">width (in pixels) of output buffer</param>
/// <param name="height">height (in pixels) of output buffer</param>
/// <returns>point in screen-space</returns>
D2D1_POINT_2F CBodyBasics::BodyToScreen(const CameraSpacePoint& bodyPoint, int width, int height)
{
// Calculate the body's position on the screen
DepthSpacePoint depthPoint = {0};
m_pCoordinateMapper->MapCameraPointToDepthSpace(bodyPoint, &depthPoint);
float screenPointX = static_cast<float>(depthPoint.X * width) / cDepthWidth;
float screenPointY = static_cast<float>(depthPoint.Y * height) / cDepthHeight;
return D2D1::Point2F(screenPointX, screenPointY);
}
/// <summary>
/// Draws a body
/// </summary>
/// <param name="pJoints">joint data</param>
/// <param name="pJointPoints">joint positions converted to screen space</param>
void CBodyBasics::DrawBody(const Joint* pJoints, const D2D1_POINT_2F* pJointPoints)
{
// Draw the bones
// Torso
DrawBone(pJoints, pJointPoints, JointType_Head, JointType_Neck);
DrawBone(pJoints, pJointPoints, JointType_Neck, JointType_SpineShoulder);
DrawBone(pJoints, pJointPoints, JointType_SpineShoulder, JointType_SpineMid);
DrawBone(pJoints, pJointPoints, JointType_SpineMid, JointType_SpineBase);
DrawBone(pJoints, pJointPoints, JointType_SpineShoulder, JointType_ShoulderRight);
DrawBone(pJoints, pJointPoints, JointType_SpineShoulder, JointType_ShoulderLeft);
DrawBone(pJoints, pJointPoints, JointType_SpineBase, JointType_HipRight);
DrawBone(pJoints, pJointPoints, JointType_SpineBase, JointType_HipLeft);
// Right Arm
DrawBone(pJoints, pJointPoints, JointType_ShoulderRight, JointType_ElbowRight);
DrawBone(pJoints, pJointPoints, JointType_ElbowRight, JointType_WristRight);
DrawBone(pJoints, pJointPoints, JointType_WristRight, JointType_HandRight);
DrawBone(pJoints, pJointPoints, JointType_HandRight, JointType_HandTipRight);
DrawBone(pJoints, pJointPoints, JointType_WristRight, JointType_ThumbRight);
// Left Arm
DrawBone(pJoints, pJointPoints, JointType_ShoulderLeft, JointType_ElbowLeft);
DrawBone(pJoints, pJointPoints, JointType_ElbowLeft, JointType_WristLeft);
DrawBone(pJoints, pJointPoints, JointType_WristLeft, JointType_HandLeft);
DrawBone(pJoints, pJointPoints, JointType_HandLeft, JointType_HandTipLeft);
DrawBone(pJoints, pJointPoints, JointType_WristLeft, JointType_ThumbLeft);
// Right Leg
DrawBone(pJoints, pJointPoints, JointType_HipRight, JointType_KneeRight);
DrawBone(pJoints, pJointPoints, JointType_KneeRight, JointType_AnkleRight);
DrawBone(pJoints, pJointPoints, JointType_AnkleRight, JointType_FootRight);
// Left Leg
DrawBone(pJoints, pJointPoints, JointType_HipLeft, JointType_KneeLeft);
DrawBone(pJoints, pJointPoints, JointType_KneeLeft, JointType_AnkleLeft);
DrawBone(pJoints, pJointPoints, JointType_AnkleLeft, JointType_FootLeft);
// Draw the joints
for (int i = 0; i < JointType_Count; ++i)
{
D2D1_ELLIPSE ellipse = D2D1::Ellipse(pJointPoints[i], c_JointThickness, c_JointThickness);
if (pJoints[i].TrackingState == TrackingState_Inferred)
{
m_pRenderTarget->FillEllipse(ellipse, m_pBrushJointInferred);
}
else if (pJoints[i].TrackingState == TrackingState_Tracked)
{
m_pRenderTarget->FillEllipse(ellipse, m_pBrushJointTracked);
}
}
}
/// <summary>
/// Draws one bone of a body (joint to joint)
/// </summary>
/// <param name="pJoints">joint data</param>
/// <param name="pJointPoints">joint positions converted to screen space</param>
/// <param name="pJointPoints">joint positions converted to screen space</param>
/// <param name="joint0">one joint of the bone to draw</param>
/// <param name="joint1">other joint of the bone to draw</param>
void CBodyBasics::DrawBone(const Joint* pJoints, const D2D1_POINT_2F* pJointPoints, JointType joint0, JointType joint1)
{
TrackingState joint0State = pJoints[joint0].TrackingState;
TrackingState joint1State = pJoints[joint1].TrackingState;
// If we can't find either of these joints, exit
if ((joint0State == TrackingState_NotTracked) || (joint1State == TrackingState_NotTracked))
{
return;
}
// Don't draw if both points are inferred
if ((joint0State == TrackingState_Inferred) && (joint1State == TrackingState_Inferred))
{
return;
}
// We assume all drawn bones are inferred unless BOTH joints are tracked
if ((joint0State == TrackingState_Tracked) && (joint1State == TrackingState_Tracked))
{
m_pRenderTarget->DrawLine(pJointPoints[joint0], pJointPoints[joint1], m_pBrushBoneTracked, c_TrackedBoneThickness);
}
else
{
m_pRenderTarget->DrawLine(pJointPoints[joint0], pJointPoints[joint1], m_pBrushBoneInferred, c_InferredBoneThickness);
}
}
/// <summary>
/// Draws a hand symbol if the hand is tracked: red circle = closed, green circle = opened; blue circle = lasso
/// </summary>
/// <param name="handState">state of the hand</param>
/// <param name="handPosition">position of the hand</param>
void CBodyBasics::DrawHand(HandState handState, const D2D1_POINT_2F& handPosition)
{
D2D1_ELLIPSE ellipse = D2D1::Ellipse(handPosition, c_HandSize, c_HandSize);
switch (handState)
{
case HandState_Closed:
m_pRenderTarget->FillEllipse(ellipse, m_pBrushHandClosed);
break;
case HandState_Open:
m_pRenderTarget->FillEllipse(ellipse, m_pBrushHandOpen);
break;
case HandState_Lasso:
m_pRenderTarget->FillEllipse(ellipse, m_pBrushHandLasso);
break;
}
}
//Added by Liu Jiaxin
//识别模块总接口